Reputation: 121
I have a column with a lot of missing values. I want to randomly replace some of these missing values (not all!) with a number, and others with another number.
Example: a column with 10000 values, some of which are missing. From those missing values, randomly select 50 and change from NA to 1. Also, randomly select another 30 missing values and changes from NA to 5.
what I've tried:
rows<- test1[test1== NA]
rows_to_replace<-sample (rows, 30, REPLACE = FALSE)
test1[rows_to_replace,]<-5
But I cant get it to work.
Some sample data
test1<-sample(c(0.5:10, NA), 10000, replace = T)
Upvotes: 1
Views: 259
Reputation: 518
Your sample data:
test1 <- sample(c(0.5:10, NA), 10000, replace = T)
Randomly select 50 NAs and replace by 1:
na_test1 <- which(is.na(test1))
test1[sample(na_test1,50)] <- 1
Randomly select 30 more and replace by 5:
na_test1 <- which(is.na(test1))
test1[sample(na_test1,30)] <- 5
Compare your solution to mine, we almost did the same. The function which()
is key here, providing the indices for NAs.
Upvotes: 1