创建移位行矩阵的for循环的替代方法

创建移位行矩阵的for循环的替代方法,r,performance,loops,for-loop,matrix,R,Performance,Loops,For Loop,Matrix,下面的代码使用一个10 x 2的矩阵,以索引和价格作为列。然后,它将可变价格移动m次,并使用移动的变量创建一个10 x m的矩阵。最后,它将该矩阵附加到原始数据帧。这是一个在大型数据库上运行的模板。如果可能的话,我想找到for循环的替代方法来提高代码的性能/速度 #Data df <- data.frame( Index = c(1:10), Price = c(1221, 1220, 1220, 1217, 1216, 1218 , 1216, 1216, 1217, 1220

下面的代码使用一个10 x 2的矩阵,以索引和价格作为列。然后,它将可变价格移动m次,并使用移动的变量创建一个10 x m的矩阵。最后,它将该矩阵附加到原始数据帧。这是一个在大型数据库上运行的模板。如果可能的话,我想找到for循环的替代方法来提高代码的性能/速度

#Data
df <- data.frame(
  Index = c(1:10),
  Price = c(1221, 1220, 1220, 1217, 1216,  1218 , 1216, 1216, 1217, 1220))

#Define rowShift function
rowShift <- function(x, shiftLen = 1L) { 
  r <- (1L + shiftLen):(length(x) + shiftLen)
  r[r<1] <- NA
  return(x[r])  }

#Pre-allocate variables/matrix for shifted rows
n <- NROW(df$Price)
m <- 5 #how many rows to shift
FwdMatrix <- matrix(nrow = n, ncol = m)
dimnames(FwdMatrix) <- list(rownames(FwdMatrix, do.NULL = FALSE, prefix = ""),colnames(FwdMatrix, do.NULL = FALSE, prefix = "Fwd"))

#Loop to create shifted rows variables
for(i in 1:m) { FwdMatrix[,i ] <- rowShift(df$Price,-i) }
Index <- df$Index
FwdMatrixBis <- cbind(FwdMatrix, Index)
FwdDF <- data.frame(FwdMatrixBis) 
df2 <- merge(df, FwdDF, by = "Index", sort = FALSE)
#数据

df您可以从
数据中使用
shift
。表
包:

library(data.table)
m <- 5
FwdMatrix <- matrix(unlist(shift(df$Price, 1L:m)), ncol=m)
库(data.table)

我喜欢FwdMatrix地狱是的!太棒了,谢谢你。想把它作为一个回答,这样我就可以检查问题的答案了吗?还有,你知道在你的代码中是否可以写“m”而不是“5”作为输入?尝试此操作时收到错误消息。