【问题标题】:mutate across (decompose) all dates in a dataframe跨越(分解)数据框中的所有日期
【发布时间】:2021-12-27 17:38:08
【问题描述】:

我的数据框中有很多日期列,需要将所有日期转换为每个日期(月、月和年)的三个新列

我尽量避免专门写下每一列,所以我使用across,但仍然围绕着这种动词来思考

library(tidyverse)

df <- tibble(dates1 = c("2020-08-03", "2020-08-03"),
           dates2 = c("2020-08-05", "2020-08-05"))


df %>% mutate(across(contains("dates"), lubridate::day(.), lubridate::month(.), lubridate::year(.) ))

Error: Problem with `mutate()` input `..1`.
i `..1 = across(...)`.
x do not know how to convert 'x' to class “POSIXlt”

并猜测应该如何命名新列......我有点迷茫

【问题讨论】:

    标签: r dplyr tidyverse across


    【解决方案1】:

    list 内尝试

    library(dplyr)
    df %>% 
       mutate(across(contains("dates"), list(day = ~ lubridate::day(.), 
           month = ~ lubridate::month(.), year = ~lubridate::year(.) )))
    

    -输出

    # A tibble: 2 × 8
      dates1     dates2     dates1_day dates1_month dates1_year dates2_day dates2_month dates2_year
      <chr>      <chr>           <int>        <dbl>       <dbl>      <int>        <dbl>       <dbl>
    1 2020-08-03 2020-08-05          3            8        2020          5            8        2020
    2 2020-08-03 2020-08-05          3            8        2020          5            8        2020
    

    【讨论】:

    • 我现在觉得有点傻。这么简单……
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多