R在矩阵中替换NA

Ric*_*rdo 1 r

在RI中有一个带有一些缺失值的数据框,因此该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)})
Run Code Online (Sandbox Code Playgroud)

但我有这个错误:

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
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

最好的Riccardo

Rei*_*son 7

您无法测试NA使用比较运算符的原因是值是NA或缺失.is.na()是以识别形式识别缺失的适当功能NA.

这是一个替换NA矩阵的例子values.这里的关键是以矢量化的方式工作,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] 0
Run Code Online (Sandbox Code Playgroud)