 # Summarize formula using a Loop Statement

Hello,

I'm trying to write a loop which will take my formula, successively assign values from a defined sequence (in my example its a sequence of (1 to 7) and then sum the values of each iteration. My code below, will return the last iterated value but not the sum of all iterated values. Is the issue related to how I am calling my interation ie using the range function? Any advice/help is much appreciated! Thanks!

``````cpnA<-30
y<-0.025
n<-8
p<-1000

for(i in range(1, n-1)){
pv<-sum((cpnA/(1+y)^i)) + ((p+cpnA)/(1+y)^8)}

``````

your code will only return the last value, as it involves an assignment to a single object pv. the last thing written into pv is the last calculation, any previous would be overwritten. Additionally range() will only set i to values of 1 and 7, if you want the integer values between also you could use seq_len(n-1)

can you please clarify if you are trying to sum independent results of your function, or whether you intend them to accumulate during an iteration ?

``````1:5

sum(1:5)

cumsum(1:5)

sum(cumsum(1:5))``````

Thanks for the clarification regarding my use of the range function. I am trying to sum independent results of my function.

OK, I am guessing you don't want to use range and I'll show why below. R is vectorized and that's important and you can avoid loops using this a lot of the time

``````cpnA<-30
y<-0.025
n<-8
p<-1000

# Look at range gives - it gives the min and max, not the sequence

range(1, n-1)
#>  1 7

(i <- 1:(n-1))  # I think you want this and not range.
#>  1 2 3 4 5 6 7

(pvsteps <- (cpnA/(1+y)^i) + ((p+cpnA)/(1+y)^8))
#>  874.6373 873.9234 873.2270 872.5475 871.8846 871.2379 870.6069
(pv <- sum(pvsteps))
#>  6108.064
``````

Created on 2021-10-25 by the reprex package (v2.0.1)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.