【问题标题】:Expand Time Into Minutes Increments将时间扩展到分钟增量
【发布时间】:2016-11-08 00:49:57
【问题描述】:

我正在尝试将时间从tstart 扩展到tstop 的分钟增量:

## 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 通话有关。 不幸的是,我无法解决这个问题。

【问题讨论】:

  • 谢谢,现在可以使用了

标签: r time dplyr data-manipulation posixct


【解决方案1】:

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

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" ...

【讨论】:

  • 啊!我应该创建一个单独的对象。它适用于样本数据。与原始问题无关的是我得到:Error in seq.int(0, to0 - from, by) : 'to' cannot be NA, NaN or infinite 尝试在minmax 语句中添加na.rm=TRUE,但没有帮助。
  • @ThomasSpeidel 能否检查一下数据中是否有Inf 元素
  • is.infinite 一排是罪魁祸首
猜你喜欢
  • 2020-11-04
  • 2019-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-03
  • 1970-01-01
相关资源
最近更新 更多