【问题标题】:Specify function arguments from string从字符串指定函数参数
【发布时间】:2020-07-20 08:41:51
【问题描述】:

我正在尝试设置要运行的函数以及要在脚本开头包含哪些参数的详细信息,以便稍后调用该函数。我无法指定要输入到函数中的参数。 我有一个固定的对象

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

我想指定我将使用哪个测量函数以及任何相关参数。

示例 1:

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

示例 2:

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

那我希望能够运行这个指定的函数

chosenFunction(v, chosenArguments)

不幸的是,我不能只输入字符串chosenArguments 并期望函数运行。有没有其他方法可以为我的函数指定参数?

【问题讨论】:

  • 您能否详细说明您想在其中使用chosenFunction()chosenArguments 的上下文?你是把它放在lapply() 电话里还是什么的?有了更清晰的背景,就更容易找到解决方案。
  • 我只想在开始时指定函数和参数,因为我在脚本中多次重复使用它们。如果我想更改我的测量功能,在整个脚本的开头更改几行会更容易。

标签: r function


【解决方案1】:

根据 OP 的说明更新答案

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

以后如果你想改变功能

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

原答案

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

通过...,您不必指定所有参数

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

【讨论】:

    【解决方案2】:

    如果我们要计算mean,我们通过

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

    另一种方法是使用do.call

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

    我们可以利用这一事实为chosenArguments 创建一个命名列表并在do.call 中使用它

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

    【讨论】:

      猜你喜欢
      • 2020-07-12
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 2011-06-24
      • 2018-03-14
      相关资源
      最近更新 更多