通过群体和重塑确定连续观察的运行

时间:2016-10-05 15:13:20

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

我正在尝试识别连续观察的运行,对它们进行分组并重新整形,以便每次运行的开始和结束占据一列。目测:

Example

## 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. 分组数据
  3. rle识别连续观察的运行 在id内(例如rle(example$event > 0)
  4. 从长到宽重塑,其中min(日期)和max(日期)(在运行中)成为列
  5. 我不知道该怎么办。 similar questiondata.table解决方案已接近,但我无法重新定位。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

这是另一种选择:

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