Skip to content
Prev 318542 / 398503 Next

cumulative sum by group and under some criteria

Hi,

It seems like you haven't even looked at the output of d2, (first d2)
d2<- cbind(d,d1)
head(d2,3)
#? m1 n1 x1 y1 p11 p12?? term1_p0?? term1_p1??? Qm??? Qn
#1? 2? 2? 0? 0?? 0 0.0 0.81450625 0.31640625 1.000 1.000
#2? 2? 2? 0? 1?? 0 0.5 0.08573750 0.21093750 0.666 0.666
#3? 2? 2? 0? 2?? 0 1.0 0.00225625 0.03515625 0.500 0.500
?ncol(d2)? # you have only 10 columns in d2
#[1] 10


#2nd problem:
You are splitting using d

###############Your code

library(zoo)
lst1<- split(d,list(d$m1,d$n1)) # should split byd2, because `d` doesn't have Qm or Qn columns? 
d2<-do.call(rbind,lapply(lst1[lapply(lst1,nrow)!=0],function(x){ 
x[,13:18]<-NA; #### this code was created for another dataset which obviously had 12 columns
x[,13:14][x$Qm<=c11,]<-cumsum(x[,11:12][x$Qm<=c11,]); #### here your term1_p0 and term1_p1 are columns 7 and 8.
x[,15:16][x$Qn<=c12,]<-cumsum(x[,11:12][x$Qn<=c12,]);
x[,17:18]<-cumsum(x[,11:12]); 
colnames(x)[13:18]<- c("cterm1_P0L","cterm1_P1L","cterm1_P0H","cterm1_P1H","sumTerm1_p0","sumTerm1_p1"); 
x1<-na.locf(x); 
x1[,13:18][is.na(x1[,13:18])]<-0; 
x1}
)) 
##########################################


#corrected codes:

lst1<- split(d2,list(d2$m1,d2$n1)) 

dNew<-do.call(rbind,lapply(lst1[lapply(lst1,nrow)!=0],function(x){
x[,11:16]<-NA;
x[,11:12][x$Qm<=c11,]<-cumsum(x[,7:8][x$Qm<=c11,]);
x[,13:14][x$Qn<=c12,]<-cumsum(x[,7:8][x$Qn<=c12,]);
x[,15:16]<-cumsum(x[,7:8]);
colnames(x)[11:16]<- c("cterm1_P0L","cterm1_P1L","cterm1_P0H","cterm1_P1H","sumTerm1_p0","sumTerm1_p1");
x1<-na.locf(x);
x1[,11:16][is.na(x1[,11:16])]<-0;
x1}
))
?row.names(dNew)<- 1:nrow(dNew)
?head(dNew,3)
#? m1 n1 x1 y1 p11 p12?? term1_p0?? term1_p1??? Qm??? Qn cterm1_P0L cterm1_P1L
#1? 2? 2? 0? 0?? 0 0.0 0.81450625 0.31640625 1.000 1.000????????? 0????????? 0
#2? 2? 2? 0? 1?? 0 0.5 0.08573750 0.21093750 0.666 0.666????????? 0????????? 0
#3? 2? 2? 0? 2?? 0 1.0 0.00225625 0.03515625 0.500 0.500????????? 0????????? 0
#? cterm1_P0H cterm1_P1H sumTerm1_p0 sumTerm1_p1
#1????????? 0????????? 0?? 0.8145062?? 0.3164062
#2????????? 0????????? 0?? 0.9002438?? 0.5273438
#3????????? 0????????? 0?? 0.9025000?? 0.5625000


A.K.
Message-ID: <1362163893.93231.YahooMailNeo@web142605.mail.bf1.yahoo.com>
In-Reply-To: <CACexUkuFAGuaXUDz+TdkDgzpnJnyBBncuym6LivPGOD5Bxe7sg@mail.gmail.com>