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**.

R-bloggers.com offers

**daily e-mail updates** about

R news and

tutorials on topics such as:

Data science,

Big Data, R jobs, visualization (

ggplot2,

Boxplots,

maps,

animation), programming (

RStudio,

Sweave,

LaTeX,

SQL,

Eclipse,

git,

hadoop,

Web Scraping) statistics (

regression,

PCA,

time series,

trading) and more...

If you got this far, why not

__subscribe for updates__ from the site? Choose your flavor:

e-mail,

twitter,

RSS, or

facebook...