简体   繁体   English

r中在一定条件下的组累计和

[英]cumulative sum by group and under some condition in r

Within the group with the same m1 and n1 , I need to calculate cumulative sum of x1 if x1 is not 0 and cumulative sum of y1 if y1 is not 0. Any help would be appreciated. 在具有相同的m1n1的组内,如果x1不为0,则需要计算x1累积和,如果y1不为0,则需要计算y1累积和。可以提供任何帮助。

 d <- data.frame () 
    for ( m1 in 2: 3) { 
         for (n1 in 2: 3){ 
              for (x1 in 0: m1) { 
                   for (y1 in 0: n1) {                                                                                                         

                  d<-rbind(d, c(m1, n1, x1,y1)) 
    }}}} 

so for m1=2 , n1=2 , the cumlative sum of x1 should be 9 and sum of y1 is 9, for m1=2 , n1=3 , the cumlative sum of x1 should be 12 and sum of y1 is 18. 因此对于m1=2n1=2x1的累积和应为9, y1为9,对于m1=2n1=3x1的累积和应为12, y1为18。

Is this what you are looking for? 这是你想要的? (using data.table ). (使用data.table )。 And I think you want to sum all the elements, and not cumulatively sum and return all elements. 而且我认为您想对所有元素求和,而不是对所有元素进行累加和返回。

# after running your code, I had to rename it
names(d) <- c("m1", "n1", "x1", "y1")
require(data.table)
dt <- data.table(d)
setkey(dt, m1, n1)
out <- dt[, list(s.x1=sum(x1), x.y1=sum(y1)),by="m1,n1"]
> out
#    m1 n1 s.x1 x.y1
# 1:  2  2    9    9
# 2:  2  3   12   18
# 3:  3  2   18   12
# 4:  3  3   24   24

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM