views:

70

answers:

1

Hopefully this has an easy answer I just haven't been able to find:

I am trying to write a simulation that will compare a number of statistical procedures on different subsets of rows (subjects) and columns (variables) of a large matrix.

Subsets of rows was fairly easy using a sample() of the subject ID numbers, but I am running into a little more trouble with columns.

Essentially, what I'd like to be able to do is create a random sample of column index numbers which will then be used to create a new matrix. What's got me the closest so far is:

testmat <- matrix(rnorm(10000),nrow=1000,ncol=100)
column.ind <- sample(3:100,20)
teststr <- paste("testmat[,",column.ind,"]",sep="",collapse=",")

which gives me a string that has a testmat[,column.ind] for every sampled index number. Is there any way to easily plug that into a cbind() function to make a new matrix? Is there any other obvious way I'm missing?

I've been able to do it using a loop (i.e. cbind(matrix,newcolumn) over and over), but that's fairly slow as the matrix I'm using is quite large and I will be doing this many times. I'm hoping there's a couple-line solution that's more elegant and quicker.

+7  A: 

Have you tried testmat[, column.ind]?

Rows and columns can be indexed in the same way with logical vectors, a set of names, or numbers for indexes.

See here for an example: http://ideone.com/EtuUN.

Shane
Ha! That worked. I knew it'd be something easy I was just blanking on. :)I'll accept your answer when it lets me... thanks!
Adam