简体   繁体   中英

Store parameters in object and call in a function

Say I have an operation that I want to perform on some data, for example, taking the means of some columns. Is there any way that I can store the function parameters, in the example below, trim and na.rm in an object, and simply call that object when using the function, instead of having to type the parameters in each time I take the mean? Please note I'm not trying to use apply, summarise all, or any of those types of functions that are more efficient in the example below.

## sample data
dat <- data.frame(x = 1:10,
                  y = 11:20)

## traditional appraoch
mean(dat$x, trim = 0.3, na.rm = T)
mean(dat$y, trim = 0.3, na.rm = T)

## desired functionality
parameters <- list(trim = 0.3, na.rm = T)
mean(dat$x, parameters)
mean(dat$y, parameters)

We can wrap it in do.call

do.call(mean,  c(list(dat$x), parameters))

Or

do.call(mean,  c(dat['x'], parameters))

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