R向量/dataframe中的基本滞后
很可能会暴露我是R的新手,但在SPSS中,运行时滞很容易。 显然这是用户错误,但我失踪了?
x <- sample(c(1:9), 10, replace = T) y <- lag(x, 1) ds <- cbind(x, y) ds 结果是:
  xy [1,] 4 4 [2,] 6 6 [3,] 3 3 [4,] 4 4 [5,] 3 3 [6,] 5 5 [7,] 8 8 [8,] 9 9 [9,] 3 3 [10,] 7 7 
我想我会看到:
  xy [1,] 4 [2,] 6 4 [3,] 3 6 [4,] 4 3 [5,] 3 4 [6,] 5 3 [7,] 8 5 [8,] 9 8 [9,] 3 9 [10,] 7 3 
任何指导将不胜感激。
解决这个问题的另一种方法是使用zoo软件包,该软件包有一个延迟方法,用NA来填充结果:
 require(zoo) > set.seed(123) > x <- zoo(sample(c(1:9), 10, replace = T)) > y <- lag(x, -1, na.pad = TRUE) > cbind(x, y) xy 1 3 NA 2 8 3 3 4 8 4 8 4 5 9 8 6 1 9 7 5 1 8 9 5 9 5 9 10 5 5 
结果是一个多元动物园对象(这是一个增强的matrix),但很容易转换为一个data.frame通过
 > data.frame(cbind(x, y)) 
我有同样的问题,但我不想使用动物园或xts,所以我写了一个简单的滞后函数的dataframe :
 lagpad <- function(x, k) { if (k>0) { return (c(rep(NA, k), x)[1 : length(x)] ); } else { return (c(x[(-k+1) : length(x)], rep(NA, -k))); } } 
这可以向前或向后滞后:
 x<-1:3; (cbind(x, lagpad(x, 1), lagpad(x,-1))) x [1,] 1 NA 2 [2,] 2 1 3 [3,] 3 2 NA 
  lag不会改变数据,只会改变“时间基础”。  x没有“时间基准”,所以cbind不能像你期望的那样工作。 尝试cbind(as.ts(x),lag(x))并注意到1的“滞后”会使期间向前移动。 
 我会build议使用zoo / xts时间序列。  zoo小插曲特别有用。 
  lag()适用于时间序列,而您正在尝试使用裸matrix。  这个老问题build议使用embed代替,如下所示: 
 lagmatrix <- function(x,max.lag) embed(c(rep(NA,max.lag), x), max.lag+1) 
例如
 > x [1] 8 2 3 9 8 5 6 8 5 8 > lagmatrix(x, 1) [,1] [,2] [1,] 8 NA [2,] 2 8 [3,] 3 2 [4,] 9 3 [5,] 8 9 [6,] 5 8 [7,] 6 5 [8,] 8 6 [9,] 5 8 [10,] 8 5 
 tmp<-rnorm(10) tmp2<-c(NA,tmp[1:length(tmp)-1]) tmp tmp2 
这应该适应vector或matrix以及负滞后:
 lagpad <- function(x, k=1) { i<-is.vector(x) if(is.vector(x)) x<-matrix(x) else x<-matrix(x,nrow(x)) if(k>0) { x <- rbind(matrix(rep(NA, k*ncol(x)),ncol=ncol(x)), matrix(x[1:(nrow(x)-k),], ncol=ncol(x))) } else { x <- rbind(matrix(x[(-k+1):(nrow(x)),], ncol=ncol(x)),matrix(rep(NA, -k*ncol(x)),ncol=ncol(x))) } if(i) x[1:length(x)] else x } 
只需使用标准的R函数,就可以以更简单的方式实现:
 x <- sample(c(1:9), 10, replace = T) y <- c(NA, head(x, -1)) ds <- cbind(x, y) ds 
只要摆脱滞后。 将您的行更改为:
 y <- c(NA, x[-1]) 
现在对我来说最简单的方法似乎是:
 require(dplyr) df <- data.frame(x = sample(c(1:9), 10, replace = T)) df <- df %>% mutate(y = lag(x)) 
一个简单的方法可能会将数据复制到新的数据框并更改索引号。 确保原始表格按顺序编入索引,无间隙
例如
 tempData <- originalData rownames(tempData) <- 2:(nrow(tempData)+1) 
如果你想在同一个数据框中使用一个cbind函数