[英]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. 在具有相同的m1
和n1
的组内,如果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=2
, n1=2
, x1
的累积和应为9, y1
为9,对于m1=2
, n1=3
, x1
的累积和应为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.