Skip to content

cumulative sum by group and under some criteria

1 message · arun

#
Hi,

""

Thanks. I tried this code below, why does expanded dataset 'res1' has m1=3 and n1=3
, dataset 'd3' doesn't have m1=3, n1=3.
?

d3<-structure(list(m1 = c(2, 3, 2), n1 = c(2, 2, 3), cterm1_P0L = c(0.9025, 
0.857375, 0.9025), cterm1_P1L = c(0.64, 0.512, 0.64), cterm1_P0H = c(0.9025, 
0.9025, 0.857375), cterm1_P1H = c(0.64, 0.64, 0.512)), .Names = c("m1", 
"n1", "cterm1_P0L", "cterm1_P1L", "cterm1_P0H", "cterm1_P1H"), row.names = c(NA, 
3L), class = "data.frame")
d3
""
d3
#? m1 n1 cterm1_P0L cterm1_P1L cterm1_P0H cterm1_P1H
#1? 2? 2?? 0.902500????? 0.640?? 0.902500????? 0.640
#2? 3? 2?? 0.857375????? 0.512?? 0.902500????? 0.640
#3? 2? 3?? 0.902500????? 0.640?? 0.857375????? 0.512

Here, there is no row with m1=3 and n1=3.? 





d2<- data.frame()??
#this was part of your original code.? In this, m1 is expanding on each value of n1
for (m1 in 2:3) { 
??? for (n1 in 2:3) { 
??????? for (x1 in 0:(m1-1)) { 
??????????? for (y1 in 0:(n1-1)) { 
??? ??? for (m in (m1+2): (7-n1)){ 
???? ??? ??? ? for (n in (n1+2):(9-m)){ 
? ??? ??? ???? for (x in x1:(x1+m-m1)){ 
??? ??? ???? for(y in y1:(y1+n-n1)){??? ?
?d2<- rbind(d2,c(m1,n1,x1,y1,m,n,x,y)) 
?}}}}}}}} 
colnames(d2)<-c("m1","n1","x1","y1","m","n","x","y")?? #Here the combination is there

?expand.grid(2:3,2:3)
#? Var1 Var2
#1??? 2??? 2
#2??? 3??? 2
#3??? 2??? 3
#4??? 3??? 3


res1<-do.call(rbind,lapply(unique(d3$m1),function(m1)
?do.call(rbind,lapply(unique(d3$n1),function(n1)
?do.call(rbind,lapply(0:(m1-1),function(x1)
?do.call(rbind,lapply(0:(n1-1),function(y1)
?do.call(rbind,lapply((m1+2):(7-n1),function(m)
?do.call(rbind,lapply((n1+2):(9-m),function(n)
?do.call(rbind,lapply(x1:(x1+m-m1), function(x)
?do.call(rbind,lapply(y1:(y1+n-n1), function(y)
?expand.grid(m1,n1,x1,y1,m,n,x,y)) ))))))))))))))) 
?names(res1)<- c("m1","n1","x1","y1","m","n","x","y") 
?attr(res1,"out.attrs")<-NULL res1[]<- sapply(d2,as.integer)? 
?res1 #here too
identical(d2,res1)
#[1] TRUE


library(plyr)
res2<- join(res1,d3,by=c("m1","n1"),type="full")? #combination with m1=3, n1=3 didn't exist in d3, so that rows are left as missing or NA

?tail(res2,3)
?# ? m1 n1 x1 y1 m n x y cterm1_P0L cterm1_P1L cterm1_P0H cterm1_P1H
#427? 3? 3? 2? 2 4 5 3 2???????? NA???????? NA???????? NA???????? NA
#428? 3? 3? 2? 2 4 5 3 3???????? NA???????? NA???????? NA???????? NA
#429? 3? 3? 2? 2 4 5 3 4???????? NA???????? NA???????? NA???????? NA


I hope it helps.


A.K.