Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

mutate across (decompose) all dates in a dataframe

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading