Home > Back-end >  mutate across (decompose) all dates in a dataframe
mutate across (decompose) all dates in a dataframe

Time:11-17

have a lot of date columns in my dataframe and needed to transform all the dates to three new columns per date (day of month, month and year)

I try to avoid to specifically write every column down, so i am using across but still wrapping my mind around this kind of verbs

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”

and guessing how the new columns should be named....I am a bit lost

CodePudding user response:

Try within a list

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

-output

# 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
  • Related