teh
teh

Reputation: 31

R: How to add a column with a randomly chosen value from each row of a matrix?

I'll preface this by saying I'm an R noob and that I think this may have an easy solution, but I'm struggling to find it.

I've got a matrix with 2 columns and 1,000 rows. Keeping the rows fixed, I'd like to create a new variable that randomly chooses one of the elements from the 2 columns. For example making a simple matrix:

        matrix(c(1,1,4,6,1,3,2,1,1,7), ncol=2)

        [,1] [,2] [,3]
  [1,]    1    3    3
  [2,]    1    2    1  
  [3,]    4    1    4
  [4,]    6    1    1
  [5,]    1    7    7

In the simplified matrix above, the 3rd column (which I just added by hand) just contains a random element from either of the prior columns in the corresponding row. My question is, how would I create such a variable in R? I don't necessarily need it to be created within the matrix itself either.

Many thanks in advance.

Upvotes: 3

Views: 1654

Answers (2)

IRTFM
IRTFM

Reputation: 263331

cbind(mat, mat[cbind( 1:NROW(mat), sample(1:2, NROW(mat), replace=TRUE) ) ] )

     [,1] [,2] [,3]
[1,]    1    3    1
[2,]    1    2    2
[3,]    4    1    4
[4,]    6    1    1
[5,]    1    7    1

Tha above method uses sampling from 1:2 along one column of an indexing matrix. Below is a method that samples along the first column and then picks the remaining rows from the second column. These might be faster if these structures were large or if many replicates were needed in simulation exercises:

 idx<-sample(c(TRUE,FALSE), prod(dim(mat))/2, replace=TRUE) # a 5 element logic vector
 cbind( mat, mat[ c(idx, !idx)] )  # using the idx and negation of the idx
     [,1] [,2] [,3]
[1,]    1    3    1
[2,]    1    2    2
[3,]    4    1    1
[4,]    6    1    1
[5,]    1    7    7

Upvotes: 5

Max
Max

Reputation: 4932

t <- matrix(c(1,1,4,6,1,3,2,1,1,7), ncol=2)
cbind(t,apply(t,1,function(x) sample(x,size=1)))

      [,1] [,2] [,3]
[1,]    1    3    1
[2,]    1    2    2
[3,]    4    1    4
[4,]    6    1    1
[5,]    1    7    1

Upvotes: 8

Related Questions