Tim K
Tim K

Reputation: 71

Specify function arguments from string

I'm trying to set up details for which function to run and which arguments to include at the start of my script, to then later call the function. I'm having trouble specifying arguments to be input into the function. I have a fixed object

v <- c(1,2,3,5,6,7,8,9,NA)

I want to specify which measurement function I will use as well as any relevant arguments.

Example 1:

chosenFunction <- mean
chosenArguments <- "trim = 0.1, na.rm = T"

Example 2:

chosenFunction <- median
chosenArguments <- "na.rm = F"

Then I want to be able to run this specified function

chosenFunction(v, chosenArguments)

Unfortunately, I can't just put in the string chosenArguments and expect the function to run. Is there any alternative way to specify the arguments to my function?

Upvotes: 1

Views: 52

Answers (2)

Drumy
Drumy

Reputation: 460

Updated answer based on OP's clarifications

chosenFunction <- mean
get_summary <- function(x, fun, ...) fun(x, ...)> 
v <- 1:100 
get_summary(v, chosenFunction, na.rm = TRUE)
# [1] 50.5

Later on if you want to change the function

chosenFunction <- median
get_summary(v, chosenFunction, na.rm = TRUE)
# [1] 50.5

Original answer

get_summary <- function(x, chosenFunction, ...) chosenFunction(x, ...)
v <- 1:100
get_summary(v, mean, na.rm = TRUE, trim = 1)
# [1] 50.5
get_summary(v, median, na.rm = TRUE)
# [1] 50.5

By doing ..., you don't have to specify all arguments

get_summary(mean, na.rm = TRUE)
# [1] 50.5

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 389265

If we want to calculate mean, we do it by

mean(v, na.rm = TRUE, time = 0.1)
#[1] 5.125

Another way is by using do.call

do.call(mean, list(v, na.rm = TRUE, trim = 0.1))
#[1] 5.125

We can leverage this fact and create a named list for chosenArguments and use it in do.call

chosenFunction <- mean
chosenArguments <- list(na.rm = TRUE, trim = 0.1)
do.call(chosenFunction, c(list(v), chosenArguments))
#[1] 5.125

Upvotes: 1

Related Questions