【问题标题】:How to create list of functions with multiple parameters from dataframes in R?如何从 R 中的数据帧创建具有多个参数的函数列表?
【发布时间】:2021-12-14 21:04:58
【问题描述】:

长期阅读,第一次海报。我没有发现任何关于我当前问题的先前问题。我想创建多个线性函数,以后可以将其应用于变量。我有一个斜率数据框: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[i,j} 但任何形式都会很棒。例如

myfunc_all[2,1]

在我们的例子中是

function (x){ x*2+4] 

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

【问题讨论】:

    标签: r dataframe function parameters


    【解决方案1】:

    因此,当您使用 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
    

    您可以选择编写一个返回函数的函数。看起来像

    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
    

    【讨论】:

    • 非常感谢,完美运行,尤其是第二个版本非常适合我的应用程序。我之前遇到过你推荐的问题,但不太明白。现在我将深入研究 mapply。
    【解决方案2】:
    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)
    

    【讨论】:

      猜你喜欢
      • 2020-07-01
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 2022-11-23
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多