0

Reference: https://stackoverflow.com/a/28056113/3942806

I am using the code from the link above to create lagged values for two columns.

n<-4
odd2<-setDT(odd)[, paste("OBS_Q", 1:n) := shift(OBS_Q, 1:n)]
odd2<-setDT(odd)[, paste("sac", 1:n) := shift(sac, 1:n)]

This works great! I get 18 columns.

But for convenience, I tried to convert it into a function:

masterlag<-function(df,col,n){
   setDT(df)[, paste(col,sep='_',1:n) := shift(df[[col]], 1:n)]
}

odd3<-masterlag(df=odd,col="OBS_Q",n=4)
odd3<-masterlag(df=odd,col="sac",n=4)

But in this case, the newly created columns of the first one ('OBS_Q') are getting replaced when I used the function the second time ('sac'). So, I am only left with 14 columns instead of 18.

Any pointers as to why?

odd<-structure(list(DATE = 19630101:19630104, PRECIP = c(0, 0, 0,0), 
               OBS_Q = c(1.61, 1.48, 1.4, 1.33), swb = c(1.75, 1.73, 1.7,1.67), 
               gr4j = c(1.9, 1.77, 1.67, 1.58), isba = c(0.83, 0.83,0.83, 0.83), 
               noah = c(1.31, 1.19, 1.24, 1.31), sac = c(1.99,1.8, 1.66, 1.57), 
               swap = c(1.1, 1.05, 1.08, 0.99), vic.mm.day. = c(2.1,1.75, 1.55, 1.43)), 
          .Names = c("DATE", "PRECIP", "OBS_Q", "swb","gr4j", "isba", "noah", "sac", "swap", "vic.mm.day."), 
          class = c("data.table","data.frame"), row.names = c(NA, -4L)) 
Community
  • 1
  • 1
maximusdooku
  • 5,242
  • 10
  • 54
  • 94

1 Answers1

1

The dataframes are self-updating

odd<-masterlag(df=odd,col="OBS_Q",n=4)
odd<-masterlag(df=odd,col="sac",n=4)
maximusdooku
  • 5,242
  • 10
  • 54
  • 94