Irakli Irakli - 1 month ago 7
R Question

R: how to apply a function that outputs a dataframe to list?

My single-argument function outputs a dataframe

library(tidyverse)
myfun <-function(x) {mtcars %>%
filter_(x) %>%
group_by(cyl) %>%
summarise(mean(disp), mean(drat)) %>%
mutate(group=x)}


When feedling a single-argument into this function, it outputs, as expected, a datafame:

myfun('mpg>15')

cyl mean(disp) mean(drat) group
4 105 4.07 mpg>15
6 183 3.59 mpg>15
8 105 3.20 mpg>15


How to apply such a function to a list of arguments so that the output is one dataframe combining all the results over the list. For example, I'd like to apply myfun to a list

c('mpg>15', 'drat>4.2')


and, as the result, to obtain a single dataframe:

cyl mean(disp) mean(drat) group
4 105 4.07 mpg>15
6 183 3.59 mpg>15
8 105 3.20 mpg>15
4 89 4.53 drat>4.2
8 351 4.22 drat>4.2


How to do that (preferably within tidyverse)?

Answer

To stay in tidyverse, maybe something like this:

c("mpg>15", "am==1") %>% map(myfun) %>% bind_rows

A mixed option, using lapply:

lapply(c("mpg>15", "am==1"), myfun) %>% bind_rows 
c("mpg>15", "am==1") %>% lapply(myfun) %>% bind_rows

Or, to get a little more perverse about mixing base and tidyverse:

c("mpg>15", "am==1") %>% lapply(myfun) %>% do.call(rbind, .)