【问题标题】:How to easily coerce all values in a multidimensional array to numeric如何轻松地将多维数组中的所有值强制为数字
【发布时间】:2015-06-16 11:46:35
【问题描述】:

所以我有一个 n X m X z 数组。它的所有值都可能是数字,但目前是字符(例如“4.02”)。有没有一种简单的方法可以将所有值强制转换为数字,而不需要经过一个大循环?例如我可以写:

for(i in 1:n){
  for(j in 1:m){
    A[i, j, ] = as.numeric(A[i, j, ])
  }
}

但这又慢又丑。有没有更好的办法?

【问题讨论】:

  • 那个循环无论如何都行不通

标签: arrays r coercion


【解决方案1】:

嗯,R 中的数组只能保存一种数据类型,所以它们要么全是数字,要么全是字符。另一种从字符更改为数字的简单方法是使用class()<-。例如

A <- array(c("4","5","6.2","7","8.8","9","10","11.5", 
    "12","12.2","13", "14.1"), dim=list(2,2,3))
str(A)
# chr [1:2, 1:2, 1:3] "4" "5" "6.2" "7" "8.8" "9" "10" ...

class(A) <- "numeric"
str(A)
# num [1:2, 1:2, 1:3] 4 5 6.2 7 8.8 9 10 11.5 12 12.2 ...
A

【讨论】:

  • 很好,我不知道你能做到这一点(我猜想重新定义类会解构数组,很酷,它没有)。
【解决方案2】:

Durp,有:

A = array(as.numeric(A), dim = dim(A), dimnames = dimnames(A))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-19
    • 2021-01-01
    • 2020-01-20
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    相关资源
    最近更新 更多