如果我在R中有一个如下所示的矩阵:
1,3 7,1 8,2
我如何编写创建如下矩阵的代码:
1,3 1,3 1,3 7,1 8,2 8,2
哪里根据右边的列重复行?请记住,我有一个矩阵实际上有比2
更多的行答案 0 :(得分:11)
# 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 , ]
答案 1 :(得分:7)
这是您的原始矩阵:
a<-matrix(c(1,7,8,3,1,2),3,2)
这使你成为第一列:
rep(a[,1],times=a[,2])
这使你成为第二列:
rep(a[,2],times=a[,2])
将这些与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
答案 2 :(得分:0)
buildConfigField "String", "EasterEggURL", null