0

I need to calculate the sum of a constant raised to a power based upon an index. For example if my constant is a rate .5 and the index is 4, I want to sum .5^1+.5^2+.5^3+.5^4 and assign this sum to an object. So my function would initiate the following:

 decay_rate = .5
index_value = 5
 expsum<-function(decay_rate, index_value) { 
decayVector <-rep(decay_rate,index_value)
indexp <-seq(1,index_value)
}

"I guess combine decayvector and indexp like a sumproduct except decayVector values would be exponents If there is a way to create this using Plyr or sapply etc... that would be great.

RayR
  • 57
  • 1
  • 9

3 Answers3

2
decay_rate = .5
index_value = 5

decind = function(rate, index){
    iv = 1:index
    sum(rate^iv)
}

decind(decay_rate, index_value)
[1] 0.96875

Or even shorter, no need to apply or anything:

sum(decay_rate^(1:index_value))
user14382
  • 959
  • 5
  • 5
  • All great help as I am learning to program in R. user14382 solution is the most efficient but I really appreciate the explanation given by Scriven, it helps me understand why? – RayR Apr 28 '14 at 13:34
0

Here's an sapply method, although as pointed out by user14382 there's no looping necessary for this problem.

> decay <- 0.5 
> index <- 5
> sum(sapply(1:index, function(x) decay^x))
## [1] 0.96875

If you want a function to do this quickly, you can simply adjust your function to

> expsum <- function(decay, index){
      sum(decay^seq(index))
  }

Then you can use it on a single decay rate, single index as

> expsum(0.5, 5)
## [1] 0.96875
> expsum(0.9, 4)
## [1] 3.0951

Or loop multiple decays and indices with mapply

> mapply(expsum, decay = c(0.5, 0.9), index = c(5, 4))
## [1] 0.96875 3.09510
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
0

This is a problem where a simple vectorized solution is available. Using a loop (or sapply, for that matter) is not recommended here, as this works comparatively slowly:

> decay_rate = .5
> index_value = 50000

Here is a vectorized solution:

> system.time(sum(decay_rate^(1:index_value)))
   user  system elapsed 
  0.005   0.000   0.006 

Here is an sapply (looping) type solution:

> system.time(sum(sapply(1:index_value, function(x) decay_rate^x)))
   user  system elapsed 
  0.112   0.009   0.139 
Shambho
  • 3,250
  • 1
  • 24
  • 37