繁体   English   中英

R用一个独特的随机数替换NA

[英]R Replacing NAs with a unique random numer

我在数据框中有一个看起来像这样的变量

x=c(1,2,4,6,7,NA,NA,5,NA,NA,9)

x中的每个元素都是唯一的数字,我想用唯一的数字替换NAs。

我试过的是这样的,但想知道是否有更有效的方法来做到这一点。

x[is.na(x)]=sample(10:15,replace=F)
Warning message:
In x[is.na(x)] = sample(10:15, replace = F) :
  number of items to replace is not a multiple of replacement length

谢谢!

如果您“计算”从候选值集中采样的项目数( is.na的总和似乎是一个很好的计数方法),那么您将不会得到错误:

x[is.na(x)] <- sample(10:15, size=sum(is.na(x)), replace=F)

> x
 [1]  1  2  4  6  7 12 14  5 11 13  9

你可以遍历并创建一个缺失值索引的向量,然后将该向量传递给replace() with random()嵌套在里面生成随机数,用你的替换缺失值。

# data
x=c(1,2,4,6,7,NA,NA,5,NA,NA,9)
# vector of missing values
v <- NULL
# loop to find missing value indices
for(i in 1:length(x)){
  if(is.na(x[i])==TRUE)
    v <- append(v, i)
}
# replace missing values with a random integer
xnew <- replace(x, v, sample(10, length(v), replace = FALSE))



x
>> 1  2  4  6  7 NA NA  5 NA NA  9
xnew
>> 1  2  4  6  7  5 10  5  4  2  9

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM