Conditional cumulative sum with apply functions in R -
may question addressed , answered in so, couldn't able find out. i'm computing cumulative sum conditions on large data frame. @ below example
data=data.frame("catg"=c("a","a","a","a","a","b","b","b","c","c","c","d","d","d","d","d","d","d","d","e","e","f"),"val"=c(67,42,12,32,28,1,11,9,38,61,75,99,22,44,89,99,51,34,82,99,74,42)) res=null uniqcatg=unique(data$catg) for(i in 1:length(uniqcatg)) res=c(res, cumsum(data[data$catg==uniqcatg[i],"val"])) data$res=res data
is there smart way without loops? (like apply functions)
or plyr::ddply
...
require( plyr ) ddply( data , "catg" , transform , res = cumsum(val) ) # catg val res #1 67 67 #2 42 109 #3 12 121 #4 32 153 #5 28 181 #6 b 1 1 #7 b 11 12 #8 b 9 21 #9 c 38 38 #10 c 61 99 #11 c 75 174 #12 d 99 99 #13 d 22 121 #14 d 44 165 #15 d 89 254 #16 d 99 353 #17 d 51 404 #18 d 34 438 #19 d 82 520 #20 e 99 99 #21 e 74 173 #22 f 42 42
Comments
Post a Comment