在矩阵N次中重复行的值

use*_*963 4 r matrix

如果我在R中有一个矩阵,如下所示:

1,3
7,1
8,2

我如何编写创建如下矩阵的代码:

1,3
1,3
1,3
7,1
8,2
8,2

它根据右侧列值重复行?请记住,我有一个矩阵实际上有比2更多的行

Ant*_*ico 13

# 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 , ]
Run Code Online (Sandbox Code Playgroud)


Jou*_*ske 8

这是你的原始矩阵:

a<-matrix(c(1,7,8,3,1,2),3,2)
Run Code Online (Sandbox Code Playgroud)

这使你成为第一列:

rep(a[,1],times=a[,2])
Run Code Online (Sandbox Code Playgroud)

这使你成为第二列:

rep(a[,2],times=a[,2])
Run Code Online (Sandbox Code Playgroud)

将这些与cbind结合起来:

cbind(rep(a[,1],times=a[,2]),rep(a[,2],times=a[,2]))

     [,1] [,2]
[1,]    1    3
[2,]    1    3
[3,]    1    3
[4,]    7    1
[5,]    8    2
[6,]    8    2
Run Code Online (Sandbox Code Playgroud)