0

我有三列,在第四列中我想要第三列的滞后。如何在 R 中做到这一点

例如

uid       timestamp    operation
 1         24-04-12    logged-in
 2         25-06-13    view content
 1         31-05-10    delete

但我想像在 SAS 中那样使用滞后功能,并希望输出如下

uid        timestamp    operation     lag
 1         24-04-12     logged-in      
 2         25-06-13     view content  logged-in
 3         31-05-10     delete        view content

我有使用 zoo 包的滞后功能,但它没有发生,如何在 R 中做到这一点?任何指导将不胜感激。

4

1 回答 1

1

当使用特定于zoo包的函数(例如?lag.zoo)时,您需要确保您正在操作的数据是一个zoo对象:

operation <- c("logged-in","view current", "delete")
lag(zoo(operation),-1,na.pad=TRUE)
#         1            2            3 
#      <NA>    logged-in view current 

lag(zoo(operation),1,na.pad=TRUE)
#           1            2            3 
#view current       delete         <NA> 

否则,使用 base R, head(and tail) 可以让你到达那里:

# match the 1 and -1 to how big you want your lag:
c(rep(NA,1),head(operation,-1))
#[1] NA             "logged-in"    "view current"

c(tail(operation,-1),rep(NA,1))
#[1] "view current" "delete"       NA   
于 2013-08-13T06:11:04.907 回答