R Replacement NA with a unique random number

I have a variable in a data frame 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 to replace NA with unique numbers.

What I tried looks like this, but was wondering if there is a more efficient way to do this.

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!

+4
source share
2 answers

If you "count" the number of elements (the sum is.nashowed a good method of counting), which will be selected from your set of candidates, then you will not get an 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
+5
source

, replace() 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
0

Source: https://habr.com/ru/post/1626613/


All Articles