Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply map function to grouped data frame in with purrr

I am trying to apply a function which takes multiple inputs (which are columns which vary depending on the problem at hand) and applying this to list of data frames. I have taken the below code from this example: Map with Purrr multiple dataframes and have those modified dataframes as the output and modified it to include another metric of my choosing ('choice'). This code, however, throws an error:

Error in .f(.x[[i]], ...) : unused argument (choice = "disp").

Ideally, I would like to be able to create a grouped data frame (with group_by or split() and apply a function over the different groups within the data frame, however have not been able to work this out. Hence looking at a list of data frames instead.

mtcars2 <- mtcars 

#change one variable just to distinguish them 
mtcars2$mpg <- mtcars2$mpg / 2

#create the list
dflist <- list(mtcars,mtcars2)

#then, a simple function example
my_fun <- function(x) 

{x <- x %>%
  summarise(`sum of mpg` = sum(mpg), 
            `sum of cyl` = sum(cyl),
            `sum of choice` = sum(choice))}

#then, using map, this works and prints the desired results
list_results <- map(dflist,my_fun, choice= "disp")
like image 435
JFG123 Avatar asked Oct 26 '25 20:10

JFG123


1 Answers

Three things to fix the code above:

  1. Add choice as an argument in your function.
  2. Make your function have an output by removing x <-
  3. Use tidyeval to make the "choice" argument work.

The edited code thus looks like this:

my_fun <- function(x, choice) 

{x %>%
summarise(`sum of mpg` = sum(mpg), 
          `sum of cyl` = sum(cyl),
          `sum of choice` = sum(!!choice))}

list_results <- map(dflist, my_fun, choice = quo(disp))

If you want to stay within a dataframe/tibble, then using nest to create list-columns might help.

mtcars2$group <- sample(c("a", "b", "c"), 32, replace = TRUE)
mtcars2 %>% 
    as_tibble() %>% 
    nest(-group) %>% 
    mutate(out = map(data, my_fun, quo(disp))) %>% 
    unnest(out)
like image 109
Mirabilis Avatar answered Oct 28 '25 10:10

Mirabilis