【问题标题】:Identify Runs of Consecutive Obs by Group and Reshape [duplicate]按组识别连续观察的运行并重塑[重复]
【发布时间】:2017-02-14 02:58:47
【问题描述】:

我正在尝试识别连续观察的运行,将它们分组并重塑,以便每次运行的开始和结束都占据一列。视觉上:

## REPRODUCIBLE EXAMPLE
> dput(example)
structure(list(id = c(123, 123, 123, 123, 123, 123, 123, 123, 
234, 234, 234), date = structure(c(1398816000, 1398902400, 1398988800, 
1399075200, 1399161600, 1350777600, 1350864000, 1350950400, 1470009600, 
1470096000, 1470182400), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
    event = structure(c(1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 
    1L), .Label = c("0", "1"), class = "factor")), row.names = c(NA, 
-11L), .Names = c("id", "date", "event"), class = c("tbl_df", 
"tbl", "data.frame"))

## GLIMPSE DATA
> dplyr::glimpse(example)
Observations: 11
Variables: 3
$ id    <dbl> 123, 123, 123, 123, 123, 123, 123, 123, 234, 234, 234
$ date  <dttm> 2014-04-30, 2014-05-01, 2014-05-02, 2014-05-03, 2014-05-04, 2012-10-21, 2012-10-22, 2012-10-23, 2016-08-01, 2016-08-02, 2016-08-03
$ event <fctr> 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0

我将方法分解如下:

  1. id分组数据
  2. rle 识别连续观察的运行 在id 内(例如rle(example$event &gt; 0)
  3. 从长到宽重塑,其中 min(date) 和 max(date)(在运行中)成为列

我不确定如何继续。 data.tablesimilar question 的解决方案很接近,但我无法重新调整它的用途。

【问题讨论】:

  • 按 id 分组,按日期排序,获取 event.start 的最小日期,获取 event.stop 的最大日期。
  • 哦,你的意思是每个 1 个 id 会有超过 1 个开始结束事件?
  • @zx8754 :每个 ID 会有多次运行,因此有多个开始和结束日期。我的最小示例没有捕捉到这一点。
  • 好的,这是一个开始见this post,想法是在id上创建组,然后使用链接发布方法使用事件列创建组id。然后按 id 和新组分组,最小最大日期...
  • 更新了可重现的示例以反映每个 ID 的多次运行

标签: r data.table aggregate reshape data-manipulation


【解决方案1】:

other post 窃取创意:

df1 %>% 
  mutate(eventGroup = data.table::rleid(event)) %>% 
  filter(event == 1) %>% 
  group_by(id, eventGroup) %>% 
  summarise(start = min(date),
            end = max(date))

#      id eventGroup      start        end
# 1   123          2 2014-05-01 2014-05-03
# 2   123          4 2012-10-22 2012-10-22
# 3   234          6 2016-08-02 2016-08-02

【讨论】:

  • 谢谢!这很好用,我个人喜欢带有一点 data.table 的 tidyverse 方法!
  • @ThomasSpeidel 有些人可能会觉得这很丑,最好坚持一个生态系统。
【解决方案2】:

这是另一个选择:

library(data.table)
setDT(ex)[,rl:=rleid(event),by=id][event=="1",.(start=min(date),stop=max(date)),by="id,rl"][,rl:=NULL][]
#     id      start       stop
# 1: 123 2014-05-01 2014-05-03
# 2: 123 2012-10-22 2012-10-22
# 3: 234 2016-08-02 2016-08-02

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-26
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多