I posted this question on Stack Overflow, which was answered successfully. But I then realised that my real-life case is considerably more complicated, and so am asking for some additional tidyverse-specific assistance.
I have a number of tibbles, each with several variables that I would like to convert to date class. Some variables are common across tables; others are not.
The linked example didn't work in real life because the lists are of different lengths.
library(purrr)
library(tibble)
library(lubridate)
df1 <- tribble(~date_a, ~ date_b, ~value_a,
"2017-1-3", "2013-7-9", 10,
"2018-2-7", "2017-6-2", 13,
"2018-5-7", "2014-8-9", 35)
df2 <- tribble(~date_b, ~date_c, ~value_b,
"2014-1-7", "2018_4_5", 10,
"2018-4-9", "2016-4-3", 6,
"2018-5-8", "2012-5-2", 18)
list_dfs <- list('df1' = df1,
'df2' = df2)
list_dates <- c("date_a", "date_b", "date_c", "date_d")
out <- map2(list_dfs, list_dates, ~ mutate_at(.x, c(.y), ymd))
#> Error: `.x` (2) and `.y` (4) are different lengths
What I want is, for each tibble within list_df
, convert any variables that appear in list_dates
to date class. Would be ideal if there was a way of doing this with no intermediary steps (i.e. mutating in place across all the tibbles).
Searching, it seems like cross2
might be a solution, but I guess the mutate_at
call will fail if a date variable doesn't appear in the tibble.
Grateful for any suggestions.