Search code examples
rmatrixsample

Sampling columns in a matrix within R


I would like to be able to sample a matrix column at random in R.

Let's say I have the matrix

x <- matrix(1:10, nrow = 5, ncol = 2)

x
     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10

To sample one column at random, I do

y <- x[sample(ncol(x), size = 1)]

However, what is returned is not a list of sorted values corresponding to either column 1 or 2 of the matrix x.

Essentially, I would like y to return either column 1 or column 2 at random, exactly as written in the matrix, but I can't seem to understand what's happening here.

Any thoughts?


Solution

  • When we are working with matrix, the indexing should be row, column (similar to data.frame - but in data.frame if we don't specify the ,, by default it will give the columns as columns are the individual units). In a matrix, the individual unit is an element. So, without the row,column, it extracts the element based on that position. To avoid that, use ,. One more thing is that when we have a single column/row, it will drop the dimensions as drop = TRUE by default for ?Extract

    x[,sample(ncol(x), size = 1), drop = FALSE]