0

I hve been trying to add a lag into an R loop but haven't been having much luck. The bare basics of my data looks like this:

N1<-1
R1<-1

N1<-(R1-3)
R2<-R1*2 #note this is different from other Rx<-... 
N2<-(R2-3)
R3<-(R2-R1)*2
N3<-(R3-3)
R4<-(R3-R2)*2
N4<-(R4-3)
R5<-(R4-R3)*2
N4<-(R4-3)
R5<-(R4-R3)*2
N4<-(R4-3)
R5<-(R4-R3)*2
etc.. to R10
print(R10)

I can turn it into a loop like so to simplify it:

N1<-1
R1<-1

N1<-(R1-3)
R2<-R1*2

n<-N1
r<-R2
for(i in 1:8) n<-(r-3)
r<-(r-("r-1"))*2
print(r)

However the "r-1" phrase (conceptually meaning the previous iteration of r, not literally meaning r minus the integer one) does not work as r is overwritten with each iteration of the loop. An ideas on how to do this? Lag functions I've read up on so far seem to require a dataframe which, as this is a model, I don't have. I'm also unsure if there's just some terminology for "r-1", or even lag, which I'm missing. Any help would be much appreciated

I K
  • 27
  • 4

2 Answers2

1

Could this be what you want:

n = 10
R <- c(1,2, rep(NA, times = n - 2))

for (i in 3:n) R[i] <- (R[i-1] + R[i-2]) * 2

R
[1]    1    2    6   16   44  120  328  896 2448 6688

N <- lag(R, 3)
[1]  NA  NA  NA   1   2   6  16  44 120 328

I think the crux here is to understand that there are "no scalars" in R. Basically everything is a vector. R[1] accesses the first value of the vector, R[2] the second one and so on and so forth.

Georgery
  • 7,643
  • 1
  • 19
  • 52
-1

A friend helped me find this solution which worked easiest for me:

N1<-1
R1<-1

N1<-(R1-3)
R2<-R1*2

n<-N1
r_prev<-R1    
r_current<-R2
for(i in 1:8) n<-(r_current-3)
r_temp<-r_current
r_current<-(r_current-r_prev)*2
r_prev<-r_temp 

print(r)

Perhaps not the neatest but a bit more simple for beginners like me!

I K
  • 27
  • 4