【问题标题】:how to shorten your code which refers to other functions [duplicate]如何缩短引用其他功能的代码[重复]
【发布时间】:2021-03-02 18:29:49
【问题描述】:

让我们考虑以下非常简单的函数:

stats <- function(x, method) {
  if (method == "mean") {
    mean(x)
  } else if (method == "median") {
    median(x)
  } else if (method == "diff") diff(x)
}

请注意,每个函数都与方法具有相同的名称(mean-mean、median-median、diff-diff)。我的问题是:有什么办法可以改变方法(作为角色)来发挥作用?所以直觉上我想要的是

stats <- function(x, method) {
  method(x)
}

它可以缩短很多事情都相同完成的非常大的代码。

你知道怎么做吗?

【问题讨论】:

    标签: r optimization


    【解决方案1】:

    你试过你的功能了吗?它确实有效。

    stats <- function(x, method) {
      method(x)
    }
    
    stats(1:10, sum)
    #[1] 55
    stats(1:10, mean)
    #[1] 5.5
    stats(1:10, diff)
    #[1] 1 1 1 1 1 1 1 1 1
    

    如果你想让一个函数接受函数名的字符值,你可以使用match.fun

    stats <- function(x, method) {
      match.fun(method)(x)
    }
    stats(1:10, "sum")
    #[1] 55
    

    【讨论】:

    • 是的,但是您提供的 sum、mean 和 diff 不带引号,这就是它起作用的原因:D
    • @John 检查更新答案以使其与引号一起使用。
    • 没错! match.fun 是我想要的!谢谢;))
    猜你喜欢
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多