[R] sum part of a vector

Weidong Gu anopheles123 at gmail.com
Sat Jul 23 13:34:01 CEST 2011


Hi Simon,

Is this what you want?

mydat$cum.news<-unlist(tapply(mydat$news,mydat$state,FUN=cumsum))

Weidong Gu

On Sat, Jul 23, 2011 at 7:11 AM, Simon Kiss <sjkiss at gmail.com> wrote:
> Dear colleagues, I have a data set that looks roughly like this;
> mydat<-data.frame(state=c(rep("Alabama", 5), rep("Delaware", 5), rep("California", 5)), news=runif(15, min=0, max=8), cum.news=rep(0, 15))
>
> For each state, I'd like to cumulatively sum the value of "news" and make that put that value in cum.news.
>
> I'm trying as follows but I get really weird results. One thing is that it keeps counting 0's as 1.
>
> for (i in levels(mydat$state)) {
> mydat[mydat$state==i, ]$cum.news<-sapply(mydat[mydat$state==i, ]$news, function(x) sum(1:x))
> }
>
> I can sort of get the same sapply function to do what I want when working on a test string
> test<-1:10
> sapply(test, function(x) sum(1:x))
>
> Any thoughts?
> Simon Kiss
> *********************************
> Simon J. Kiss, PhD
> Assistant Professor, Wilfrid Laurier University
> 73 George Street
> Brantford, Ontario, Canada
> N3T 2C9
> Cell: +1 905 746 7606
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list