Here you will find daily news and tutorials about R, contributed by over 750 bloggers.
There are many ways to follow us - By e-mail:On Facebook: If you are an R blogger yourself you are invited to add your own R content feed to this site (Non-English R bloggers should add themselves- here)

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 their blog: Paleocave Blog » R.