Skip to content
Prev 317915 / 398506 Next

cumulative sum by group and under some criteria

Hi,
""suppose that I have a dataset 'd' 
?? m1? n1??? A???????????? B???? C???????? D
1? 2? 2?? 0.902500??? 0.640?? 0.9025??? 0.64
2? 3? 2?? 0.857375??? 0.512?? 0.9025??? 0.64
I want to add? x1 (from 0 to m1), y1(from 0 to n1), m (range from 
m1+2 to 7-n1), n(from n1+2 to 9-m), x (x1 to x1+m-m1), y(y1 to y1+n-n1), expanding to another dataset 'd2' based on each row (combination of m1 
and n1)""


Try:


?d<-read.table(text="
m1? n1??? A???????????? B???? C???????? D
1? 2? 2?? 0.902500??? 0.640?? 0.9025??? 0.64
2? 3? 2?? 0.857375??? 0.512?? 0.9025??? 0.64
",sep="",header=TRUE)

vec1<- paste(d[,1],d[,2],d[,3],d[,4],d[,5],d[,6])
res1<- do.call(rbind,lapply(vec1,function(m1) do.call(rbind,lapply(0:(as.numeric(substr(m1,1,1))),function(x1) do.call(rbind,lapply(0:(as.numeric(substr(m1,3,3))),function(y1) do.call(rbind,lapply((as.numeric(substr(m1,1,1))+2):(7-as.numeric(substr(m1,3,3))),function(m) do.call(rbind,lapply((as.numeric(substr(m1,3,3))+2):(9-m),function(n)
?do.call(rbind,lapply(x1:(x1+m-as.numeric(substr(m1,1,1))), function(x)
?do.call(rbind,lapply(y1:(y1+n-as.numeric(substr(m1,3,3))), function(y)
?expand.grid(m1,x1,y1,m,n,x,y)) )))))))))))))
names(res1)<- c("group","x1","y1","m","n","x","y")
?res1$m1<- NA; res1$n1<- NA; res1$A<- NA; res1$B<- NA; res1$C<- NA;res1$D <- NA 
res1[,8:13]<-do.call(rbind,lapply(strsplit(as.character(res1$group)," "),as.numeric))
res2<- res1[,c(8:9,2:7,10:13)]


?head(res2)
#? m1 n1 x1 y1 m n x y????? A??? B????? C??? D
#1? 2? 2? 0? 0 4 4 0 0 0.9025 0.64 0.9025 0.64
#2? 2? 2? 0? 0 4 4 0 1 0.9025 0.64 0.9025 0.64
#3? 2? 2? 0? 0 4 4 0 2 0.9025 0.64 0.9025 0.64
#4? 2? 2? 0? 0 4 4 1 0 0.9025 0.64 0.9025 0.64
#5? 2? 2? 0? 0 4 4 1 1 0.9025 0.64 0.9025 0.64
#6? 2? 2? 0? 0 4 4 1 2 0.9025 0.64 0.9025 0.64
Message-ID: <1361311794.89908.YahooMailNeo@web142601.mail.bf1.yahoo.com>
In-Reply-To: <CACexUkvcuqduZ9_Z9XWQJe3Cj-FfbKF8e_qHagJYZ=QZbzrkhA@mail.gmail.com>