【问题标题】:R: Using user input to pass functions and parameters as parameters to higher-order functionsR:使用用户输入将函数和参数作为参数传递给高阶函数
【发布时间】:2016-03-12 19:37:56
【问题描述】:

我不确定这是否可行(至少我尝试这样做的方式),但我真的希望如此。我有一个在 R 中开发的相当复杂的测试环境,如果我可以将函数及其相关参数作为参数传递给高阶函数,那将非常有帮助。我可以在不要求用户输入的情况下轻松做到这一点,但是 readline() 导致字符串的事实使我想做的事情有点棘手。这是一个简化版本(请注意,我假设参数输入是一个数值,但实际上,我是在我的真实代码中检查数据类型的错误。这只是为了理解这一点而进行的简化):

read_in <- function(){
    temp_nm <- readline(prompt = paste("Enter the name of parameter: "))
    temp_vlu <- as.numeric(readline(prompt = paste("Enter the value for ",temp_nm,": ")))
    assign(temp_nm,temp_vlu,envir = .GlobalEnv)
    temp_param <- as.name(temp_nm)
    temp_params <- list(temp_param)
    return(temp_params)
}

我知道这不太行,因为它返回以下内容:

> read_in()
Enter the name of parameter: this_param
Enter the value for  this_param : 12
[[1]]
this_param

这很接近,因为它确实将值 12 分配给了全局环境中的 this_param,但我真的很想返回

> read_in()
Enter the name of parameter: this_param
Enter the value for  this_param : 12    
[[1]]
this_param = 12

所以我可以将 this_param = 12 作为参数传递给另一个高阶函数(除了 this_param 作为参数的实际函数之外)。同样,与我实际尝试做的事情相比,这非常简单,将一系列函数和相关参数作为参数传递给高阶函数,同时使用 UI 而不是手动输入对我的高阶函数的调用这将很长并且容易出现人为错误。一般来说,弄清楚如何实现我上面列出的内容将极大地帮助我的发展,所以任何输入都将不胜感激。谢谢!

【问题讨论】:

  • 你看过范围赋值运算符&lt;&lt;-吗?

标签: r functional-programming higher-order-functions


【解决方案1】:

使用do.call,您可以将命名列表传递给函数

read_in <- function() {
  temp_nm <- readline(prompt = paste("Enter the name of parameter: "))
  temp_vlu <- as.numeric(readline(prompt = paste("Enter the value for ",temp_nm,": ")))
  setNames(list(temp_vlu), temp_nm)
}

f <- function(x, y, some_param) {
  some_param
}

out <- read_in()
# Enter the name of parameter: some_param
# Enter the value for  some_param : 12
# some_param 
#         12 

do.call('f', out)
# [1] 12

【讨论】:

  • 完全道歉,我现在就这样做。谢谢你的头!
猜你喜欢
  • 2016-02-24
  • 1970-01-01
  • 2011-10-18
  • 2013-01-27
  • 1970-01-01
  • 2020-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多