变换R中多个矩阵类的有效方法

ddrv8njm  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(131)

我有几个矩阵,我想应用一些类似的东西
class(matrix) <- "numeric",即所有矩阵的类应该改变为数字。
你知道怎么做吗?
dput(matrix[1:3,])结果为structure(c(285.789361223578, 282.564165145159, 273.633228540421, 256.789452806115, 260.808130130172, 241.718192100525, 266.765343174338, 267.881099879742, 250.710165724158, 284.365977942944, 281.670583188534, 268.735618144274, 264.118778035045, 262.856532484293, 254.31867428124, 286.250801086426, 284.585711210966, 268.984649181366, 286.17267370224, 284.429456442595, 267.478255555034, 275.10055847466, 274.141056537628, 259.477523118258, 246.454664766788, 252.470473349094, 232.699362188578, 284.998321458697, 283.73363442719, 269.555955678225, 0, 0, 0), dim = c(3L, 11L), dimnames = list(NULL, c("", "", "", "", "", "", "", "", "", "", "vec")))

wkftcu5l

wkftcu5l1#

在本例中,当前环境的所有矩阵变量都转换为数值。请参阅矩阵无法转换为数字的情况下的警告。

var1 <- matrix(1:10, 5, 2)
var2 <- matrix(as.character(5:13), 3,3)
var3 <- letters[1:5]
var4 <- matrix(letters[1])

print(sapply(mget(ls()), typeof))
#>        var1        var2        var3        var4 
#>   "integer" "character" "character" "character"

for (i in ls()[sapply(mget(ls()), is.matrix)])
  assign(i, as.numeric(get(i)))
#> Warning in assign(i, as.numeric(get(i))): NAs introduced by coercion

print(sapply(mget(ls()), typeof))
#>           i        var1        var2        var3        var4 
#> "character"    "double"    "double" "character"    "double"

创建于2023-06-03带有reprex v2.0.2

相关问题