[R] sum variable as long condition is true

marcg mdgi at gmx.ch
Tue Oct 23 13:51:36 CEST 2007


Hello R

For expierienced user, the following problem will be easy to solve:

a<-c(0,1,0,1,0,2,3,4,3,2)
b<-c(3,3,3,4,4,4,7,7,7,10)
c<-data.frame(a,b)

Data Frame c contains tow colums. I would like to sum up all values in a as long as b stays the same:

sum(a[which(b==1)])

does this, but i have to manually put in b

then i tryied st like this, but i canno't save it properly

for (i in 0:max(b)){
	i<-sum(a[which(b==i)])
}

i tried to figure out, how tapply works, but neither

thanks alot

marc
--



More information about the R-help mailing list