0

I have number of columns in my dataset and I need to shift columns 18:101 down by one row. So far, I found this command in another thread to be helfpul and below I apply it to my data:

data.xts$AR2_Forecast <- transform(data.xts$AR2_Forecast, AR2_Forecast = c(NA, AR2_Forecast[-nrow(data.xts$AR2_Forecast)]))

However, since I have 83 additional columns, changing the names would be quite time-consuming. Is there anything I could use that would save me the time?

I was thinking of something along the lines of:

data.xts[18:101]<-

but I am not sure how the transform function should look. The class of my data is "xts", "zoo".

Thanks for any feedback!

2 Answers2

0

I think you can use dplyr::select() along with dplyr::lag() to do this more efficiently.

Nikhil Gupta
  • 1,436
  • 12
  • 15
0

You could use the same approach as for one column, e.g. by doing:

df[, 18:101] <- rbind(rep(NA, 101-17), df[seq_len(nrow(df)-1), 18:101] )

Edit: For xts, try:

df[, 18:101] <- rbind(rep(NA, 101-17), coredata(df[1:(nrow(df)-1), 18:101] ))
user12728748
  • 8,106
  • 2
  • 9
  • 14