在矩阵中重复行N的值N次 [英] Repeat the values of a row in matrix N number of times

查看:67
本文介绍了在矩阵中重复行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次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆