In response to some comments received, here´s what I am trying to do:
- Replicate an XLS formula that works fine. The below is the beginning of what that XLS formula does
- The complete XLS formula basically interpolates input variables along a time horizon (say 120 months). For example if you ONLY input mo 1 (along vector_1) = .25 (along vector_2), mo 2 (along vector_1) = .50 (along vector_2), XLS outputs mo 1 = .25, mo 2 = .50, mos 3-120 = 0. If you ONLY input mo 1 = 2 and month 3 = 4, then XLS interpolates and output is mo 1 = 2, mo 2 = 3, mo 3 = 4, mo 5-120 = 0. If you ONLY input mo 3 = 2, then output is mo 1 = 2, mo 2 = 2, mo 3 = 2, mo 4-120= 0. Etc. This R snippet is only the beginning of this formula
- So all I am trying to do below, for now, is assign vector_2 variables along the mos 1-120 time scale, and if the current period in time horizon (vector_1) > period in the 1-120 scale, then a 0 value is returned.
I was worried about posting this, this is difficult to express clearly. And I want to learn enough to be able to do the rest of this on my own. Best way to learn!
I´m new to R and come from Excel/VBA world. I´m slowly converting an Excel formula to R equivalent. Will eventually change this to a function and explore using SEQ instead of this FOR loop. But for now, what am I doing wrong with the below? I don´t understand why I get NA in the 5th position of the output vector and 9 output elements instead of 10.
Code:
n_periods = 10
vector_1 <- c(1,2,3,4)
vector_2 <- c(0.20,0.10,0.05,0.3)
a=ifelse(vector_1[1] < 1, 0, vector_2[1])
for(i in 1:n_periods){
if(period[i+1] > max(vector_1)){a[i+1]=0} else {a[i+1] = vector_2[i+1]}
}
a
The output is below, whereby (i) the 5th position should show a 0 and not NA, (ii) there should be 10 output elements instead of 9 and (iii) I do not understand why I get that error message (output I´m looking for is 0.20 0.10 0.05 0.30 0.00 0.00 0.00 0.00 0.00 0.00):
Error in if (period[i + 1] > max(vector_1)) { :
missing value where TRUE/FALSE needed
> a
[1] 0.20 0.10 0.05 0.30 NA 0.00 0.00 0.00 0.00