Olivier Grimard
Olivier Grimard

Reputation: 77

Summation series in R

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]))

Upvotes: 6

Views: 1628

Answers (5)

Maël
Maël

Reputation: 51974

Package spatstat.utils provides a fast version ("under certain conditions") of the reverse cumulative sum, revcumsum, which is based on computing sum(x[i:n]) with n = length(x) (basically @Jan Brederecke's answer):

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)

# install.packages("spatstat.utils")
spatstat.utils::revcumsum(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

Benchmark

x = 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)
bm <- microbenchmark(
  fRev(x),
  fReduce(x),
  fJan(x), 
  fEshita(x), 
  fsapply(x),
  fRevcumsum(x),
  times = 100L
)
autoplot(bm)

rev(cumsum(rev(Lx))) and spatstat.utils::revcumsum(Lx) seem like the fastest solutions.

enter image description here

Upvotes: 2

Eshita Zaman
Eshita Zaman

Reputation: 11

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".

Upvotes: 1

lroha
lroha

Reputation: 34416

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

Upvotes: 14

PaulS
PaulS

Reputation: 25323

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

Upvotes: 2

user12484155
user12484155

Reputation:

Using a for loop:

Tx_new <- vector(length = length(Lx))
for (i in 1:length(Lx)) {
  
  Tx_new[i] <- sum(Lx[i:length(Lx)])
  
}

Upvotes: 1

Related Questions