使用dplyr在行之间进行difftime

Tim*_* S. 4 r plyr dplyr

我正在尝试使用dplyr包计算两个相邻行中两个时间戳之间的时间差.这是代码:

    tidy_ex <- function () {

    library(dplyr)

    #construct example data
    data <- data.frame(code = c(10888, 10888, 10888, 10888, 10888, 10888, 
                                    10889, 10889, 10889, 10889, 10889, 10889,
                                    10890, 10890, 10890),
                           station = c("F1", "F3", "F4", "F5", "L5", "L7", "F1",
                                       "F3", "F4", "L5", "L6", "L7", "F1", "F3", "F5"),
                           timestamp = c(1365895151, 1365969188, 1366105495,
                                           1367433149, 1368005216, 1368011698,
                                           1366244224, 1366414926, 1367513240,
                                           1367790556, 1367946420, 1367923973,
                                           1365896546, 1365907968, 1366144207))

    # reformat timestamp as POSIXct
    data$timestamp <- as.POSIXct(data$timestamp,origin = "1970-01-01")

    #create tbl_df
    data2 <- tbl_df(data)

    #group by code and calculate time differences between two rows in timestamp column 
    data2 <- data2 %>%
            group_by(code) %>%
            mutate(diff = c(difftime(tail(timestamp, -1), head(timestamp, -1))))

    data2

    }
Run Code Online (Sandbox Code Playgroud)

该代码生成错误消息:

 Error: incompatible size (5), expecting 6 (the group size) or 1
Run Code Online (Sandbox Code Playgroud)

我想这是因为最后一行的差异产生了一个NA(因为没有更多的相邻行).然而,difftime/head-tails方法适用于plyr包而不是dplyr (参见此StackOverflow文章)

如何使用dplyr使其工作?

Tim*_* S. 5

感谢Victorp的建议.我将mutate行改为:

mutate(diff = c(difftime(tail(timestamp, -1), head(timestamp, -1)),0))
Run Code Online (Sandbox Code Playgroud)

(我放在最后的0,所以差异计算将从第一行开始).

  • `difftime(timestamp,lag(timestamp))`会更简单一些 (12认同)