A Command for Randomly Creating Sets of Elements from a Vector

R-bloggers 2013-05-02

(This article was first published on Econometrics by Simulation, and kindly contributed to R-bloggers)
# This command pairs (of arbitrary length) together a list of items randomly. # I think it is useful for simulations matching individuals together. pairup = function(x, ncol=2, unmatched.self=T) {   # Calculate the length of the x vector.   xleng = length(x)   # This checks if the input vector is a scalar.   # If it is then it assumes that the number of that scalar is to be the last number is the seqence 1:x   if (xleng==1) x = 1:(xleng=x)   # This command is pretty weird.  I combined two commands to make a single line command.   # It sets the xleng equal to x and x equal to the sequence 1:x   # Calculate the length of each column that will be created.   hleng = floor(xleng/ncol)   # Randomize x   x = x[order(runif(xleng))]   pair = x[1:hleng]   for (i in 2:ncol) pair = cbind(pair,x[((i-1)*hleng+1):((i)*hleng)])   # If there is a odd number of xs then this will match the remaining unmatched x with itself if unmatched.self is T.   if ((unmatched.self)&(floor(xleng/ncol)!=xleng/ncol)) pair=rbind(pair, c(x[ncol*hleng+1]))   if ((!unmatched.self)&(floor(xleng/ncol)!=xleng/ncol)) print(x[!(x %in% pair)])   return (pair) } pairup(1:10) pairup(99) pairup(letters) pairup(letters, ncol=3) pairup(letters, ncol=3, unmatched.self=F)

To leave a comment for the author, please follow the link and comment on his blog: Econometrics by Simulation.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series,ecdf, trading) and more...