MGJ-123
MGJ-123

Reputation: 634

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)
}

Upvotes: 0

Views: 215

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174476

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)
}

Upvotes: 2

Related Questions