简体   繁体   中英

How to use mapply to mutate columns in a list of dataframes

I have a list of dataframes - some dataframes in this list require their columns to mutated into date columns. I was wondering if it possible to do this with mapply.

Here is my attempt (files1 is the list of dataframes, c("data, data1") are the names of dataframes within files1, c("adfFlowDate","datedate") are the names of the columns within the respective dataframes:

files2 <- repair_dates(files1, c("data, data1"), c("adfFlowDate","datedate"))

The function that does not work:

repair_dates <- function(data, df_list, col_list) {
mapply(function(n, i) data[[n]] <<- data[[n]] %>% mutate(i = as.Date(i, origin = "1970-01-01")), df_list, col_list)
return(data)
}

Your set-up is fairly complex here, calling an anonymous function inside an mapply inside another function, which takes three parameters, all relating to a single nested object.

Personally, I wouldn't add to this complexity by accommodating the non-standard evaluation required to get mutate to work here (though it is possible). Perhaps something like this (though difficult to tell without any reproducible data) -

repair_dates <- function(data, df_list, col_list) 
{
  mapply(function(n, i) {
           data[[n]][[i]] <- as.Date(data[[n]][[i]], origin = "1970-01-01")
           return(data[[n]])
         }, df_list, col_list, SIMPLIFY = FALSE)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM