I am currently trying to simplify this summation, I am new to R
data:
Lx = c(5050.0, 65.0, 25.0, 19.0, 17.5, 16.5, 15.5, 14.5, 13.5, 12.5, 6.0, 0.0)
summation series
Tx = c(sum(Lx[1:12]),sum(Lx[2:12]),sum(Lx[3:12]),sum(Lx[4:12]),
sum(Lx[5:12]),sum(Lx[6:12]),sum(Lx[7:12]),sum(Lx[8:12]),
sum(Lx[9:12]),sum(Lx[10:12]),sum(Lx[11:12]),sum(Lx[12:12]))
Thank you
CodePudding user response:
You can do:
rev(cumsum(rev(Lx)))
[1] 5255.0 205.0 140.0 115.0 96.0 78.5 62.0 46.5 32.0 18.5 6.0 0.0
Or alternatively, using Reduce()
:
Reduce(` `, Lx, right = TRUE, accumulate = TRUE)
[1] 5255.0 205.0 140.0 115.0 96.0 78.5 62.0 46.5 32.0 18.5 6.0 0.0
CodePudding user response:
Using a for loop:
Tx_new <- vector(length = length(Lx))
for (i in 1:length(Lx)) {
Tx_new[i] <- sum(Lx[i:length(Lx)])
}
CodePudding user response:
A possible solution, using sapply
:
sapply(1:12, function(x) sum(Lx[x:12]))
#> [1] 5255.0 205.0 140.0 115.0 96.0 78.5 62.0 46.5 32.0 18.5
#> [11] 6.0 0.0
CodePudding user response:
Please try the following code:
Lx = c(5050.0, 65.0, 25.0, 19.0, 17.5, 16.5, 15.5, 14.5, 13.5, 12.5, 6.0, 0.0)
l=length(Lx)
aa=list()
for(i in 1:l)
{
x=sum((Lx[i:l]))
aa=append(aa,x)
}
all the values after summation will be in the list "aa".