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

落花浮王杯 提交于 2020-01-04 01:29:09

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/8046428/r-how-to-add-a-column-with-a-randomly-chosen-value-from-each-row-of-a-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!