如何从 R 中的数据帧创建具有多个参数的函数列表?

How to create list of functions with multiple parameters from dataframes in R?

好久了reader,第一次发贴。我没有发现任何关于我当前问题的先前问题。我想创建多个线性函数,稍后我可以将其应用于变量。我有一个斜率数据框:df_slopes 和一个常数数据框:df_constants。 虚拟数据:

df_slope <- data.frame(var1 = c(1, 2, 3,4,5), var2 = c(2,3,4,5,6), var3 = c(-1, 1, 0, -10, 1))
df_constant<- data.frame(var1 = c(3, 4, 6,7,9), var2 = c(2,3,4,5,6), var3 = c(-1, 7, 8, 0, -1))

我想构造函数如

myfunc <- function(slope, constant, trvalue){
result <- trvalue*slope+constant
return(result)}

其中斜率和常数值是

slope<- df_slope[i,j]
constant<- df_constant[i,j]

我尝试了很多方法,例如像这样,用for循环创建一个函数数据框

myfunc_all<-data.frame()
for(i in 1:5){
   for(j in 1:3){
     myfunc_all[i,j]<-function (x){ x*df_slope[i,j]+df_constant[i,j] }
     full_func[[i]][j]<- func_full
   }
  }

没有成功。斜率常数值配对,例如 df_slope[i,j] 与 df_constant[i,j] 配对。所需的最终结果将是某种数据框,我可以从中通过给函数提供坐标来调用函数,例如: myfunc_all[我,j} 但任何形式都会很棒。例如

myfunc_all[2,1]

在我们的例子中是

function (x){ x*2+4] 

我可以将其应用于不同的 x 值。我希望我的问题很清楚。

df_slope <- data.frame(var1 = c(1, 2, 3,4,5), var2 = c(2,3,4,5,6), var3 = c(-1, 1, 0, -10, 1))
df_constant<- data.frame(var1 = c(3, 4, 6,7,9), var2 = c(2,3,4,5,6), var3 = c(-1, 7, 8, 0, -1))

functions  = vector(mode = "list", length = nrow(df_slope))

for (i in 1:nrow(df_slope)) {
  functions[[i]] = function(i,x) { df_slope[i]*x + df_constant[i]}
}

f = function(i, x) {
  functions[[i]](i, x)
}

f(1, 1:10)
f(3, 5:10)

因此,当您使用 for 循环构建函数时,惰性求值和变量作用域会遇到一个小问题(有关详细信息,请参阅 here)。使用 mapply 之类的东西会为您创建闭包会更安全一些。尝试

myfunc_all <- with(expand.grid(1:5, 1:3), mapply(function(i, j) {
  function(x) {
    x*df_slope[i,j]+df_constant[i,j]
  }
},Var1, Var2))
dim(myfunc_all) <- c(5,3)

这将创建一个类似于对象的数组。唯一的区别是您需要使用双括号来提取函数。例如

myfunc_all[[2,1]](0)
# [1] 4
myfunc_all[[5,3]](0)
# [1] -1

备选你可以选择写一个函数即returns一个函数。那看起来像

myfunc_all <- (function(slopes, constants) {
  function(i, j)
    function(x) x*slopes[i,j]+constants[i,j]
})(df_slope, df_constant)

然后不使用括号,而是使用括号调用函数。

myfunc_all(2,1)(0)
# [1] 4
myfunc_all(5,3)(0)
# [1] -1