0

I'm trying to lag some variables in a DataFrame (and am expressly avoiding using time series), and am getting a funny result. To be precise, I'm trying to assemble a number of lags into a single object, i.e. a 1- and 2-period lag of the column called "orders." Here's what I'm doing:

time=18:29
orders=c(76,77,78,79,72,81,79,85,93,81,72,60)

 data=data.frame(time=time,orders=orders)

 lagage<-lag(data$orders, k=-1:-2)

Error in `tsp<-`(`*tmp*`, value = p - (k/p[3L]) * c(1, 1, 0)) : 
invalid time series parameters specified
In addition: Warning messages:
1: In if (k != round(k)) { :
the condition has length > 1 and only the first element will be used
2: In (k/p[3L]) * c(1, 1, 0) :
 longer object length is not a multiple of shorter object length

I'm pretty confused by why I'm getting this error as I've used the lag() function many times before with no issues. Maybe it's a brain fart on my side, but I wanted to check with you guys to see what's going on.

EDIT

Should have been more clear here-- I'm looking to fill the indexes that are affected with lags by NAs. The lagging I showed above works of I coerce the dataframe to a zoo object, like so:

data<-as.zoo(data)
lagage<-lag(data$orders, k=-1:-3)


  lag-1 lag-2 lag-3
2     76    NA    NA
3     77    76    NA
4     78    77    76
5     79    78    77
6     72    79    78
7     81    72    79
8     79    81    72
9     85    79    81
10    93    85    79
11    81    93    85
12    72    81    93

Of course, I can re-coerce the new data back to a data frame, but want to avoid these steps.

4

2 回答 2

2

在上一个答案的基础上,试试这个:

foo <- function(k) c(rep(NA, abs(k)), lag(data$orders, k=k)[abs(k):length(data$orders)])
sapply(-1:-2, foo)

lag对于一个向量将返回一个相同长度的向量,当您将它们组合到一个数据框或矩阵中时,您将得到相同的系列。它不会填充 NA 并在最后删除元素,这是滞后于数据框或矩阵时想要的。

于 2013-07-29T16:27:41.427 回答
2

请尝试以下操作:

 sapply(-1:-2, function(k) lag(data$orders, k=k))

, simplify=FALSE如果您想保留属性,您可能想要使用

于 2013-07-29T14:35:23.503 回答