我在数据框中有一个看起来像这样的变量
x=c(1,2,4,6,7,NA,NA,5,NA,NA,9)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
谢谢!
如果您"计算" 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
Run Code Online (Sandbox Code Playgroud)