将列表应用于输出数据框的函数 [英] Apply a list to a function that outputs a dataframe
问题描述
我的单参数函数输出数据框
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 feeding a single-argument into this function, it outputs, as expected, a dataframe:
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
如何将这样的函数应用于参数列表,以便输出是组合列表中所有结果的一个数据框。例如,我想将myfun应用到列表中
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)?
推荐答案
留在 tidyverse
,可能是这样的:
c("mpg>15", "am==1") %>% map(myfun) %>% bind_rows
但是,如@alistaire点在评论中,您可以使用 map_df
缩短此数据,返回数据框架:
But, as @alistaire points out in a comment, you can shorten this by using map_df
, which returns a data frame:
c("mpg>15", "am==1") %>% map_df(myfun)
混合选项,三个等效的方式,使用 lapply
:
A mixed option, three equivalent ways, using lapply
:
lapply(c("mpg>15", "am==1"), myfun) %>% bind_rows
c("mpg>15", "am==1") %>% lapply(myfun) %>% bind_rows
bind_rows(lapply(c("mpg>15", "am==1"), myfun))
或者,要对混合基础和整理有一点更加有害:
Or, to get a little more perverse about mixing base and tidyverse:
c("mpg>15", "am==1") %>% lapply(myfun) %>% do.call(rbind, .)
对于基础R传统主义者:
And for base R traditionalists:
do.call(rbind, lapply(c("mpg>15", "am==1"), myfun))
这篇关于将列表应用于输出数据框的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!