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!
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 ?
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] 1 7
(i <- 1:(n-1)) # I think you want this and not range.
#> [1] 1 2 3 4 5 6 7
(pvsteps <- (cpnA/(1+y)^i) + ((p+cpnA)/(1+y)^8))
#> [1] 874.6373 873.9234 873.2270 872.5475 871.8846 871.2379 870.6069
(pv <- sum(pvsteps))
#> [1] 6108.064