1
#Want data frame to go from this...
a<- c(1,2,3,4,5)
b<- c(0,0,0,0,0)
ab<-cbind(a,b)
print(ab)
  a b
[1,] 1 0
[2,] 2 0
[3,] 3 0
[4,] 4 0
[5,] 5 0

#to this...

     a  b
[1,] 1 15
[2,] 2 14
[3,] 3 12
[4,] 4  9
[5,] 5  5

what's happening here is to have the first value of column b to be the sum of the whole column (1+2+3+4+5=15). Its the column sum.

What we want for the next value of column b is to be the column sum of everything but the first row (2+3+4+5= 14)

The third column should be (3+4+5 =12) and so on for n number of rows.

Ive tried to make a for loop however I haven't had any success.

I'm stuck trying to figure out a way to sum a column value and everything below it using R. This is part of a lifetable calculation for ecology and any help would be appreciated.

thelatemail
  • 91,185
  • 12
  • 128
  • 188
rmcm
  • 23
  • 2

3 Answers3

3

You could use rev function:

a<- c(1,2,3,4,5)
b <- rev(cumsum(rev(a)))
cbind(a, b)
Onyambu
  • 67,392
  • 3
  • 24
  • 53
1
sum(a) - c(0, cumsum(a)[-length(a)])
# [1] 15 14 12  9  5
d.b
  • 32,245
  • 6
  • 36
  • 77
0

One way can be using a loop like this:

#Data
a<- c(1,2,3,4,5)
b<- c(0,0,0,0,0)
ab<-data.frame(a,b)
#Loop
for(i in 1:nrow(ab))
{
  ab$b[i] <- sum(ab$a[i:nrow(ab)])
}

Output:

ab
  a  b
1 1 15
2 2 14
3 3 12
4 4  9
5 5  5
Duck
  • 39,058
  • 13
  • 42
  • 84