Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Replacing NAs with a unique random numer

Tags:

replace

r

unique

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!

like image 547
user3641630 Avatar asked Jan 30 '16 01:01

user3641630


1 Answers

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
like image 185
IRTFM Avatar answered Sep 28 '22 10:09

IRTFM