【问题标题】:Extract minimum and maximum date using dplyr使用 dplyr 提取最小和最大日期
【发布时间】:2019-08-01 05:26:38
【问题描述】:

在每个子组(a、b、c、d 等)加入 4 个具有最小和最大日期的数据场后,最终数据帧具有以下列:

Id   a_min_date_df1  a_max_date_df1  a_min_date_df2   a_max_date_df2  a_min_date_df3    a_max_date_df3  a_min_date_df4   a_max_date_df4
1    2014-01-01      2014-01-10       NA              NA               NA                NA             2014-02-20       2014-05-01
2    2014-02-01      2014-02-10       NA              NA               2015-02-20       2015-03-01             NA               NA

对于某些 ID,我只能从 2 个数据帧中的 1 个而不是所有 4 个数据帧中获得最小和最大日期。

我要补充:

  • 具有每个子组(a、b、c、d 等)最小日期列的最小日期的新列

  • 具有每个子组(a、b、c、d 等)最大日期列的最大日期的新列

  • 计算新的最大和最小日期之间差异的列,如果差异超过 365 天, 比我想调整新的最小和最大日期并用原始日期替换它们:a_min_date_df1 和 a_max_date_df1

我已经尝试过了,它可以工作,但是 df 有超过 500 个子组,我无法为每个子组手动完成。

mutate(df, a_min= pmin(a_min_date1_df1, a_min_date1_df2, a_min_date1_df3, a_min_date1_df4, na.rm=TRUE), 
a_max= pmax(a_max_date1_df1, a_max_date1_df2, a_max_date1_df3, a_max_date1_df4, na.rm=TRUE)

我开始用 mutate(df, a_min= pmin(setdiff(starts_with("a_"), ends_with(min_date), na.rm=TRUE), a_max= pmax(setdiff(starts_with("a_ "), ends_with(min_date), na.rm=TRUE)) 这对我不起作用。欢迎所有建议。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    可以试试:

    library(dplyr)
    
    df %>%
      mutate_at(vars(-Id), list(~ as.Date(as.character(.)))) %>%
      mutate(pmx = pmax(!!! syms(select(., contains("max")) %>% names), na.rm = T),
             pmn = pmin(!!! syms(select(., contains("min")) %>% names), na.rm = T),
             diffr = pmx - pmn,
             pmx = case_when(diffr > 365 ~ a_max_date_df1, TRUE ~ pmx),
             pmn = case_when(diffr > 365 ~ a_min_date_df1, TRUE ~ pmn)
      )
    

    输出:

      Id a_min_date_df1 a_max_date_df1 a_min_date_df2 a_max_date_df2 a_min_date_df3 a_max_date_df3 a_min_date_df4
    1  1     2014-01-01     2014-01-10           <NA>           <NA>           <NA>           <NA>     2014-02-20
    2  2     2014-02-01     2014-02-10           <NA>           <NA>     2015-02-20     2015-03-01           <NA>
      a_max_date_df4        pmx        pmn    diffr
    1     2014-05-01 2014-05-01 2014-01-01 120 days
    2           <NA> 2014-02-10 2014-02-01 393 days
    

    【讨论】:

    • 谢谢 arg0naut!我收到以下错误。 charToDate(x) 中的错误:字符串不是标准的明确格式
    • 这意味着一旦您以良好的Date 格式获取日期,代码就会运行。不幸的是,如果不知道您可以使用dput 提供的确切数据框,您将无法提供更多帮助。
    • 我想删除从 a_max_date_df1 复制到 pmax 的 NA。我试过这个 case_when (diffr> 365 & !is.na(a_max_date_df1) ~ a_max_date_df1, TRUE ~ pmx),但得到一个错误:Ops.Date(left) 中的错误:一元!未为“日期”对象定义
    • 无法复制 - 能不能通过 dput 分享相关数据,太好了
    • 尝试了几次之后,如果我添加 !is.na,case_when 似乎也可以工作。 case_when (diffr> 365 & !is.na(a_max_date_df1) ~ a_max_date_df1, TRUE ~ pmx)。
    猜你喜欢
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 2022-10-13
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多