gpt4 book ai didi

r - 创建矩阵行索引,当 rowsum > 100 时递增,随后行

转载 作者:行者123 更新时间:2023-12-04 16:26:50 26 4
gpt4 key购买 nike

我有一个矩阵:

mat <- matrix(c(2,11,3,1,2,4,55,65,12,4,6,6,7,9,3,23,16,77,5,5,7),ncol = 3, byrow = TRUE)

[,1] [,2] [,3]
[1,] 2 11 3
[2,] 1 2 4
[3,] 55 65 12
[4,] 4 6 6
[5,] 7 9 3
[6,] 23 16 77
[7,] 5 5 7

我想添加一个带有行索引的列。该索引将从 1 开始并重复相同的索引,直到它到达 rowsums > 100 的行以移动到下一个值。
  Indx[,2][,3][,4]
[1,] 1 2 11 3
[2,] 1 1 2 4
[3,] 2 55 65 12
[4,] 3 4 6 6
[5,] 3 7 9 3
[6,] 4 23 16 77
[7,] 5 5 5 7

最佳答案

使用 rle:

matRle <- rle(rowSums(mat) > 100)$lengths

cbind(rep(seq(length(matRle)), matRle), mat)
# [,1] [,2] [,3] [,4]
# [1,] 1 2 11 3
# [2,] 1 1 2 4
# [3,] 2 55 65 12
# [4,] 3 4 6 6
# [5,] 3 7 9 3
# [6,] 4 23 16 77
# [7,] 5 5 5 7

关于r - 创建矩阵行索引,当 rowsum > 100 时递增,随后行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51866766/

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