在R中,我有一个缺少一些值的数据框,因此read.table()函数使用NAs而不是空白单元格。
我写了以下内容:
a <- sample(1000:50000000, size=120, replace=TRUE)
values <- matrix(a, nrow=6, ncol=20)
mtx <- cbind.data.frame(values, c(rep(NA),6))
mtx <- apply(mtx, 2, function(x){
if (x==NA) sample(100:500, replace=TRUE, size=nrow(mtx)) else (x)})但是我有这个错误:
Error in if (x == NA) sample(100:500, replace = TRUE, size = nrow(mtx)) else (x) :
missing value where TRUE/FALSE needed
In addition: Warning message:
In if (x == NA) sample(100:500, replace = TRUE, size = nrow(mtx)) else (x) :
the condition has length > 1 and only the first element will be used有什么想法吗?
最佳里卡多
发布于 2012-06-21 22:52:38
您不能使用比较运算符来测试NA,因为值为NA或缺失。is.na()是以NA的形式识别缺失的适当函数。
下面是在矩阵values中替换NA的示例。这里的关键是以矢量化的方式工作,只识别哪些元素是NA的,然后使用索引将所有的NA替换为所需的值。
> set.seed(2)
> values <- matrix(sample(1000:50000000, size=120, replace=TRUE),
+ nrow=6, ncol=20)
> ## add some NA to simulate
> values[sample(120, 20)] <- NA
>
> ## how many NA
> (tot <- sum(is.na(values)))
[1] 20
>
> ## replace the NA
> values[is.na(values)] <- sample(100:500, tot, replace=TRUE)
>
> ## now how many NA
> (sum(is.na(values)))
[1] 0https://stackoverflow.com/questions/11140650
复制相似问题