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))
Frage
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.
Lösung
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))
Andere Tipps
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
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