本文介绍了在矩阵中重复行N的值N次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我在R中有一个如下所示的矩阵:
If I have a matrix in R that looks like the below:
1,3 7,1 8,2我将如何编写创建如下矩阵的代码:
How would I write code that creates a matrix like this:
1,3 1,3 1,3 7,1 8,2 8,2它根据正确的.column值在哪里重复行?请记住,我有一个矩阵,实际上它的行比2多得多.
Where it repeats the row based on the right .column value? Keep in mind I have a matrix that actually has a lot more rows than 2
推荐答案# construct your initial matrix x <- matrix( c( 1 , 3 , 7 , 1 , 8 , 2 ) , 3 , 2 , byrow = TRUE ) # take the numbers 1 thru the number of rows.. 1:nrow(x) # repeat each of those elements this many times x[ , 2 ] # and place both of those inside the `rep` function rows <- rep( 1:nrow(x) , x[ , 2 ] ) # ..then return exactly those rows! x[ rows , ] # or save into a new variable y <- x[ rows , ]
更多推荐
在矩阵中重复行N的值N次
发布评论