简体   繁体   中英

Using a generic function in dplyr summarise_all

I am trying to use summarise_all() inside of a function to apply a generic function to all columns of a data frame. It looks like this:

my_func <- function(df, FUN = sum, ...) {

    < ...more stuff here ....>

    # aggregate on desired level across all columns
    df %>% group_by(level) %>% summarise_all(funs(FUN(., ...)))
}

The problem is, however, that my_func always uses the default sum function, even if I call it like:

my_func(my.data.frame, FUN="mean") # or my_func(my.data.frame, FUN=mean)

And passing in additional params for the ... argument also does not work.

What am I doing wrong?

One options is to use funs_ instead of funs .

The function would then look like

my_func <- function(df, FUN = "sum", ...) {
    df %>% 
        group_by(level) %>% 
        summarise_all(funs_(FUN, args = ...))
}

To use the args , the ... arguments would need to be put in a list.

my_func(datasetname, FUN="mean", list(na.rm = TRUE))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM