Reputation: 588
I've got a list of 17 dataframes and a list of 17 dates. They are ordered and correspond to each other. In other words, list_of_dfs[[1]]
corresponds to dates[[1]]
and so forth. The list of dates, below, are date objects using lubridate::ymd
.
> dates
[1] "2004-10-10" "2005-10-10" "2006-10-10" "2007-10-10" "2008-10-10" "2009-10-10" "2010-10-10" "2011-10-10" "2012-10-10" "2013-10-10" "2014-10-10" "2015-10-10" "2016-10-10" "2017-10-10"
[15] "2018-10-10" "2019-10-10" "2020-10-10"
I would like to mutate a subset of variables in each dataframe such that I am subtracting the subset from the corresponding object in dates
. For example, I could do the following for the first item.
list_of_dfs[[1]] <- list_of_dfs[[1]] %>% `
mutate_at(.vars = vars(contains('string')),
.funs = funs(dates[[1]] - .)
Is there a way that I incorporate the above into a map
or lapply
like command that will allow me to iterate through dates
?
My closet approximation would be something like
list_of_dfs <- list_of_dfs %>%
map(., function(x) mutate_at(x,
.vars = vars(contains('string')),
.funs = funs(dates - .)))
which can't take a list object in .funs
as shown above.
Upvotes: 1
Views: 638
Reputation: 887851
We can use map2
as we are doing the subtraction from corresponding elements of 'dates' list
library(dplyr)
library(purrr)
list_of_dfs2 <- map2(list_of_dfs, dates, ~ {date <- .y
.x %>%
mutate_at(vars(contains('string')), ~ date - as.Date(.))})
In the devel version of dplyr
, across
can be used along with mutate
list_of_dfs2 <- map2(list_of_dfs, dates, ~ { date <- .y
.x %>%
mutate(across(contains('string'), ~ date - as.Date(.x)))
})
list_of_dfs <- list(data.frame(string1 = Sys.Date() - 1:6, string2 = Sys.Date()),
data.frame(string1 = Sys.Date() - 1:6, string2 = Sys.Date()))
dates <- Sys.Date() + 1:2
Upvotes: 1