【问题标题】:How to lag row number in R如何在R中滞后行号
【发布时间】:2013-08-14 14:48:16
【问题描述】:

我有三列,在第四列中我想要第三列的滞后。如何在 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 中做到这一点? 任何指导将不胜感激。

【问题讨论】:

    标签: r lag


    【解决方案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> 
    

    否则,使用基础 R,head(和 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   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 2017-08-21
      • 1970-01-01
      • 1970-01-01
      • 2017-12-08
      相关资源
      最近更新 更多