1

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)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.