Other sites

Insert random NAs in a vector in R

I was recently writing a function which was going to need to deal with NAs in some kind of semi-intelligent way. I wanted to test it with some fake data, meaning that I was going to need a vector with some random NAs sprinkled in. After a few disappointing google searches and a stack overflow post or two that left something to be desired, I sat down, thought for a few minutes, and came up with this.

#create a vector of random values

foo <- rnorm(n=100, mean=20, sd=5)

#randomly choose 15 indices to replace
#this is the step in which I thought I was clever
#because I use which() and %in% in the same line
ind <- which(foo %in% sample(foo, 15))

#now replace those indices in foo with NA
foo[ind]<-NA

#here is our vector with 15 random NAs
foo

Not especially game changing but more elegant than any of the solutions I found on the interwebs, so there it is FTW.

Related

To leave a comment for the author, please follow the link and comment on his blog: Paleocave Blog » R.