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.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With