4

The problem in question would be to apply the function f to each group of a tibble. It is a simpler way to do this, but I would like to solve the problem using the group_map() function.

Data used: starwars of the dplyr package.

What I want is to get an average of the height variable for a grouped tibble considering the variables gender and species. I know the problem could be easily solved by doing:

starwars %>% group_by(gender, species) %>% summarise(mean = mean(height, na.rm = TRUE)) 

However, my desire is to implement summarise(mean = mean(height, na.rm = TRUE)) in a function and send to group_map().

I tried to create the f() function that gets the data argument which is a tibble object with the previously defined groups. The second argument of the f() function would be ... so that I could pass the variables of interest from data to f().

f <- function(dados, ...){ dados %>% summarise(mean = mean(..., na.rm = TRUE)) } starwars %>% group_by(gender, species) %>% group_map(.tbl = ., .f = ~f(dados = .x), height) 
4
  • 1
    You need to use tidyeval in your function. See the vignette on it Commented May 16, 2019 at 13:38
  • 1
    Using ... in your example implies that you want to get means of multiple columns. Is that the case, or do you want to just pass in one column to get the mean of? Commented May 16, 2019 at 13:47
  • Hi Camile, thanks for the info. tidyeval serves me but I'll think how to do for multiple variables. It can be a good exercise. Commented May 16, 2019 at 13:58
  • 1
    See Chapter 8 of the Tidy Evaluation book. It is very close to what you are trying to do. Commented May 16, 2019 at 14:22

1 Answer 1

2

Solutions:

func_1 <- function(dados, var, ...){ var_interesse <- enquo(var) dots <- enquos(...) # Could be attributed direct reference ... dados %>% group_by(!!!dots) %>% summarise(media = mean(x = !!var_interesse, na.rm = TRUE)) } starwars %>% func_1(var = height, gender, species) 

or

func_2 <- function(dados, var){ var_interesse <- enquo(var) #dots <- enquos(...) dados %>% summarise(media = mean(x = !!var_interesse, na.rm = TRUE)) } agrupamento <- starwars %>% group_by(gender, species) agrupamento %>% group_map(.tbl = ., .f = ~func_2(dados = .x, var = height)) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.