首页 > 解决方案 > 如何过滤不同行中的日期?

问题描述

假设我有一个数据框

abc<- children_info
child_name  custody_start   custody_end
jon         01/01/2018      04/29/2018
jon         05/01/2018      05/25/2018
jon         05/29/2018      07/31/2018
paul        03/22/2018      07/15/2019
paul        06/09/2019      03/28/2020

我想过滤每个孩子的第一个监护开始日期和最后一个监护结束日期,并在新列中对其进行变异。在 dplyr 包中,最好的方法是什么?

标签: rdplyr

解决方案


这个怎么样:

library(dplyr)
mydat %>%
  mutate_at(vars(custody_start, custody_end), ~ as.Date(., "%m/%d/%Y")) %>%
  group_by(child_name) %>%
  summarize(
    custody_start = min(custody_start),
    custody_end = max(custody_end)
  )
# # A tibble: 2 x 3
#   child_name custody_start custody_end
#   <chr>      <date>        <date>     
# 1 jon        2018-01-01    2018-07-31 
# 2 paul       2018-03-22    2020-03-28 

数据:

mydat <- read.table(header=TRUE, stringsAsFactors=FALSE, text="
child_name  custody_start   custody_end
jon         01/01/2018      04/29/2018
jon         05/01/2018      05/25/2018
jon         05/29/2018      07/31/2018
paul        03/22/2018      07/15/2019
paul        06/09/2019      03/28/2020")

推荐阅读