简体   繁体   English

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

[英]R Replacing NAs with a unique random numer

I have a variable in a dataframe that looks something like this 我在数据框中有一个看起来像这样的变量

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

Each element in x is a unique number and I want replace NAs with unique numbers. x中的每个元素都是唯一的数字,我想用唯一的数字替换NAs。

What I have tried is something like this but was wondering if there is a more efficient way to do it. 我试过的是这样的,但想知道是否有更有效的方法来做到这一点。

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

Thanks! 谢谢!

If you "count" the number of items ( the sum of is.na 's seemed a good counting method) to be sampled from your candidate set of values, then you won't get the error: 如果您“计算”从候选值集中采样的项目数( 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

You could loop through and create a vector of missing value indices and then pass that vector into replace() with random() nested inside to generate the random numbers that you was to replace the missing values with. 你可以遍历并创建一个缺失值索引的向量,然后将该向量传递给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