gpt4 book ai didi

重复矩阵中一行的值 N 次

转载 作者:行者123 更新时间:2023-12-03 18:16:08 24 4
gpt4 key购买 nike

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

1,3
7,1
8,2

我将如何编写代码来创建这样的矩阵:

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

它在哪里根据正确的 .column 值重复行?请记住,我有一个矩阵实际上有比 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 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15143829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com