将时间扩展为分钟增量

时间:2016-11-08 00:49:58

标签: r time dplyr data-manipulation posixct

我试图将时间从tstart扩展为tstop到<{1}}:

## Make reproducible example
> dput(df)
structure(list(id = c(101, 101, 101, 101, 101, 101, 101, 104, 
104, 104, 104, 104, 104, 104, 104), tstart = structure(c(1427191679, 
1427278247, 1427656267, 1427668088, 1427710073, 1427710123, 1427717538, 
1429282892, 1429923963, 1430137643, 1430270378, 1430270408, 1430430281, 
1431435022, 1431691603), class = c("POSIXct", "POSIXt"), tzone = ""), 
    tstop = structure(c(1427192645, 1427279046, 1427656779, 1427668511, 
    1427710123, 1427710556, 1427718113, 1429283349, 1429924393, 
    1430138070, 1430270408, 1430270857, 1430430872, 1431435865, 
    1431692517), class = c("POSIXct", "POSIXt")), event.seq = c(10, 
    11, 12, 13, 14, 14, 15, 10, 11, 12, 13, 13, 14, 15, 16)), class = "data.frame", row.names = c(NA, 
-15L), .Names = c("id", "tstart", "tstop", "event.seq"))


## Expand into multiple rows of 1 min increments start=tstart stop=tstop
df <- df %>%
  group_by(id, event.seq) %>%
  summarize(tstart = min(tstart), tstop = max(tstop)) %>%
  do(data.frame(minutes = seq(.$tstart, .$tstop, by = "1 min")))

这会导致错误:

Error in seq.POSIXt(.$tstart, .$tstop, by = "1 min") : 
  'from' must be of length 1

我怀疑与seq.POSIXt电话有关。 不幸的是,我无法解决这个问题。

1 个答案:

答案 0 :(得分:2)

原因是在summarise步骤之后,group_by效果消失了。一种方法是在rowwise()之前添加do

res<- df %>% 
        group_by(id, event.seq) %>% 
        summarize(tstart = min(tstart), tstop = max(tstop))  %>% 
        rowwise() %>% 
        do(data.frame(., minutes = seq(.$tstart, .$tstop, by = "1 min")))
str(res)
#Classes ‘rowwise_df’, ‘tbl_df’, ‘tbl’ and 'data.frame': 140 obs. of  5 variables:
#$ id       : num  101 101 101 101 101 101 101 101 101 101 ...
#$ event.seq: num  10 10 10 10 10 10 10 10 10 10 ...
#$ tstart   : POSIXct, format: "2015-03-24 15:37:59" "2015-03-24 15:37:59" "2015-03-24 15:37:59" "2015-03-24 15:37:59" ...
#$ tstop    : POSIXct, format: "2015-03-24 15:54:05" "2015-03-24 15:54:05" "2015-03-24 15:54:05" "2015-03-24 15:54:05" ...
#$ minutes  : POSIXct, format: "2015-03-24 15:37:59" "2015-03-24 15:38:59" "2015-03-24 15:39:59" "2015-03-24 15:40:59" ...