b = c(1,1,2,2,3,3,4,4,1)
c = c(10,10,20,20,30,30,40,40,5)
a <- NULL
a <- matrix(c(b,c), ncol=2)
我想要做的是比较数字在这个矩阵的第一列,如果第一个数字等于列中的第二个连续数字(在这种情况下,如果1 = 1,依此类推),那么我想在第二列中添加相应的数字(如10 + 10 = 20,依此类推),这只是一个值,然后我想将此输出存储在一个单独的向量中。
我正在寻找的矩阵的输出如下:
[,1] [,2] [,3]
[1,] 1 10 20
[2,] 1 10 40
[3,] 2 20 62
[4,] 2 20 85
[5,] 3 30 5
[6,] 3 32
[7,] 4 40
[8,] 4 45
[9,] 1 5
我对R很陌生并且正在努力解决这个问题。提前谢谢!
答案 0 :(得分:1)
base
解决方案,但我在rollsum
包中试用了zoo
:
library(zoo)
mm <- cbind(c(1, 1, 2, 2, 3, 3, 4, 4, 1), c(10, 10, 20, 20, 30, 30, 40, 40, 5))
# calculate all lagged sums of column 2
sums <- rollsum(x = mm[ , 2], k = 2)
# calculate differences between consecutive numbers in column 1
diffs <- diff(mm[ , 1])
# select sums where diff is 0, i.e. where the two consecutive numbers in column 1 are equal.
sums2 <- sums[diffs == 0]
sums2
# [1] 20 40 60 80