dplyr - 安排,分组,计算日期差异

时间:2016-07-09 21:15:35

标签: r dplyr

我有一个大型数据集,显示从“健康”事件到随后的“病态”事件的孩子的跟进

我正在尝试使用dplyr来计算“健康”事件和第一次“生病”事件之间的时间

模拟数据集

 id <- c(1,1,1,1,1,1) 
event <- c("healthy","","","sick","sick","")
date_follow_up <- c("4/1/15", "4/2/15", "4/3/15", "4/4/15", "4/5/15", "4/6/15")

df1 <- data_frame(id, event, date_follow_up)

模拟输出数据集

id <- c(1,1,1,1,1,1) 
event <- c("healthy","","","sick","sick","")
date_follow_up <- c("4/1/15", "4/2/15", "4/3/15", "4/4/15", "4/5/15", "4/6/15")
diff_time <- c(3,"","","","","")

df1 <- data_frame(id, event, date_follow_up, diff_time)

我只能使用dplyr按“id”和“date_follow_up”对数据进行排序,然后按“id”分组:

df2 <- df1 %>% arrange(id, date_follow_up) %>% group_by(id)

请计算日期差异并将其添加到行旁边,并为每个人添加“健康”事件,这需要帮助:)

5 个答案:

答案 0 :(得分:3)

使用@ akrun的示例数据,这是使用来自 data.table 滚动连接的一种方式:

require(data.table)
dt = as.data.table(mydf)[, date_follow_up := as.Date(date_follow_up, format="%m/%d/%y")][]
dt1 = dt[event == "healthy"]
dt2 = dt[event == "sick"]

idx = dt2[dt1, roll = -Inf, which = TRUE, on = c("id", "date_follow_up")]

这个想法是:对于每个健康的日期(在dt1中),获取第一个生病日期(dt2>=的健康日期的索引。

然后直接减去两个日期以获得最终结果。

dt[event == "healthy", 
     diff := as.integer(dt2$date_follow_up[idx] - dt1$date_follow_up)]

答案 1 :(得分:2)

我对您的数据进行了一些修改以彻底检查此案例。我的建议与alistaire建议的类似。我的建议可以在mydf中为id 2生成NA,而alistaire建议会创建Inf。首先,我将您的日期(字符)转换为日期对象。然后,我将数据按id分组,并通过减去healthy的第一天计算时差(即date_follow_up[event == "healthy"][1] )从sick的第一天开始(即date_follow_up[event == "sick"][1])。最后,我用NA替换了不相关行的时差。

   id   event date_follow_up
1   1 healthy         4/1/15
2   1                 4/2/15
3   1                 4/3/15
4   1    sick         4/4/15
5   1    sick         4/5/15
6   2                 4/1/15
7   2 healthy         4/2/15
8   2                 4/3/15
9   2                 4/4/15
10  2                 4/5/15
11  3                 4/1/15
12  3 healthy         4/2/15
13  3    sick         4/3/15
14  3                 4/4/15
15  3                 4/5/15

library(dplyr)
mutate(mydf, date_follow_up = as.Date(date_follow_up, format = "%m/%d/%y")) %>%
group_by(id) %>%
mutate(foo = date_follow_up[event == "sick"][1] - date_follow_up[event == "healthy"][1],        
       foo = replace(foo, which(event != "healthy"), NA))


Source: local data frame [15 x 4]
Groups: id [3]

      id   event date_follow_up            foo
   <int>   <chr>         <date> <S3: difftime>
1      1 healthy     2015-04-01         3 days
2      1             2015-04-02        NA days
3      1             2015-04-03        NA days
4      1    sick     2015-04-04        NA days
5      1    sick     2015-04-05        NA days
6      2             2015-04-01        NA days
7      2 healthy     2015-04-02        NA days
8      2             2015-04-03        NA days
9      2             2015-04-04        NA days
10     2             2015-04-05        NA days
11     3             2015-04-01        NA days
12     3 healthy     2015-04-02         1 days
13     3    sick     2015-04-03        NA days
14     3             2015-04-04        NA days
15     3             2015-04-05        NA days

数据

mydf <- structure(list(id = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 
3L, 3L, 3L, 3L, 3L), event = c("healthy", "", "", "sick", "sick", 
"", "healthy", "", "", "", "", "healthy", "sick", "", ""), date_follow_up = c("4/1/15", 
"4/2/15", "4/3/15", "4/4/15", "4/5/15", "4/1/15", "4/2/15", "4/3/15", 
"4/4/15", "4/5/15", "4/1/15", "4/2/15", "4/3/15", "4/4/15", "4/5/15"
)), .Names = c("id", "event", "date_follow_up"), row.names = c(NA, 
-15L), class = "data.frame")

答案 2 :(得分:2)

我们也可以使用data.table。转换&#39; data.frame&#39;到&#39; data.table&#39; (setDT(mydf)),使用Date将&#39; date_follow_up的类更改为as.Date,按&#39; id&#39;分组通过获取逻辑向量(event == "healthy")的累积和来创建分组变量,我们得到了&#39; date_follow_up&#39;对于第一个&#34;病人&#34; &#39;事件&#39;第一个&#39; date_follow_up&#39; (这将是&#34;健康&#34;)ifany&#34;生病&#34; &#39;事件&#39;在该特定群组或else返回&#34; NA&#34;。

library(data.table)
setDT(mydf)[, date_follow_up := as.Date(date_follow_up, "%m/%d/%y")
    ][, foo := if(any(event == "sick"))  
                  as.integer(date_follow_up[which(event=="sick")[1]] - 
                         date_follow_up[1] )
                else NA_integer_ , 
     by = .(grp= cumsum(event == "healthy"), id)]

然后,我们可以改变&#34; foo&#34;到&#34; NA&#34;为所有&#34;事件&#34;那不健康&#34;。

mydf[event!= "healthy", foo := NA_integer_]
mydf
#    id   event date_follow_up foo
# 1:  1 healthy     2015-04-01   3
# 2:  1             2015-04-02  NA
# 3:  1             2015-04-03  NA
# 4:  1    sick     2015-04-04  NA
# 5:  1    sick     2015-04-05  NA
# 6:  2             2015-04-01  NA
# 7:  2 healthy     2015-04-02  NA
# 8:  2             2015-04-03  NA
# 9:  2             2015-04-04  NA
#10:  2             2015-04-05  NA
#11:  3             2015-04-01  NA
#12:  3 healthy     2015-04-02   1
#13:  3    sick     2015-04-03  NA
#14:  3             2015-04-04  NA
#15:  3             2015-04-05  NA
#16:  4             2015-04-01  NA
#17:  4 healthy     2015-04-02   3
#18:  4             2015-04-03  NA
#19:  4             2015-04-04  NA
#20:  4    sick     2015-04-05  NA
#21:  4    sick     2015-04-06  NA
#22:  4             2015-04-07  NA
#23:  4 healthy     2015-04-08   2
#24:  4             2015-04-09  NA
#25:  4    sick     2015-04-10  NA

注意:在这里,我准备了数据,其中可能有多个&#34;健康/生病&#34; &#39;事件&#39;特定的&#34; id&#34;。

数据

mydf <- structure(list(id = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 
3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4), event = c("healthy", "", 
"", "sick", "sick", "", "healthy", "", "", "", "", "healthy", 
"sick", "", "", "", "healthy", "", "", "sick", "sick", "", "healthy", 
"", "sick"), date_follow_up = c("4/1/15", "4/2/15", "4/3/15", 
"4/4/15", "4/5/15", "4/1/15", "4/2/15", "4/3/15", "4/4/15", "4/5/15", 
"4/1/15", "4/2/15", "4/3/15", "4/4/15", "4/5/15", "4/1/15", "4/2/15", 
"4/3/15", "4/4/15", "4/5/15", "4/6/15", "4/7/15", "4/8/15", "4/9/15", 
"4/10/15")), .Names = c("id", "event", "date_follow_up"), row.names = c(NA, 
25L), class = "data.frame")

答案 3 :(得分:0)

这是一种方法,但如果每个ID有多个“健康”事件,您可能需要对其进行调整以使其更加健壮:

        # turn dates into subtractable Date class
df1 %>% mutate(date_follow_up = as.Date(date_follow_up, '%m/%d/%y')) %>% 
    group_by(id) %>%
           # Add new column. If there is a "healthy" event,
    mutate(diff_time = ifelse(event == 'healthy', 
                              # subtract the date from the minimum "sick" date
                              min(date_follow_up[event == 'sick']) - date_follow_up, 
                              # else if it isn't a "healthy" event, return NA.
                              NA))

## Source: local data frame [6 x 4]
## 
##      id   event date_follow_up diff_time
##   <dbl>   <chr>         <date>     <dbl>
## 1     1 healthy     2015-04-01         3
## 2     1             2015-04-02        NA
## 3     1             2015-04-03        NA
## 4     1    sick     2015-04-04        NA
## 5     1    sick     2015-04-05        NA
## 6     1             2015-04-06        NA

答案 4 :(得分:0)

这是使用library(dplyr) df1$date_follow_up <- as.Date(df1$date_follow_up, "%m/%d/%y") df1 %>% group_by(id, event) %>% filter(event %in% c("healthy", "sick")) %>% slice(which.min(date_follow_up)) %>% group_by(id) %>% mutate(diff_time = lead(date_follow_up) - date_follow_up) %>% right_join(df1, by = c("id", "event" , "date_follow_up")) # Output Source: local data frame [6 x 4] Groups: id [?] id event date_follow_up diff_time <dbl> <chr> <date> <S3: difftime> 1 1 healthy 2015-04-01 3 days 2 1 2015-04-02 NA days 3 1 2015-04-03 NA days 4 1 sick 2015-04-04 NA days 5 1 sick 2015-04-05 NA days 6 1 2015-04-06 NA days 的另一种方法(尽管与早期解决方案相比有点长)

{{1}}