[R] sum part of a vector
Simon Kiss
sjkiss at gmail.com
Sat Jul 23 13:11:57 CEST 2011
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
More information about the R-help
mailing list