【问题标题】:R apply a formula in a for loopR在for循环中应用公式
【发布时间】:2022-11-19 02:15:02
【问题描述】:

我想创建一个函数,其中一个数学公式被设置为参数(只有两个可能的变量)并在两个嵌套循环中使用这个公式。我的想法是能够更改公式,因为我想根据公式创建 y 值。这是我所做的,但我无法应用该公式:

foo <- function(formula = y~a-b){
formula = as.formula(y ~a -b)
formula = formula[[3:length(formula)]]
result = NULL
for (a in 1:30) {
 for(b in 1:30){
  result = c(result, noquote(formula))
 }
}
return(result)
}

【问题讨论】:

    标签: r formula


    【解决方案1】:

    创建一个模板 fun,然后将公式插入其主体。

    foo <- function(formula = y ~ a - b) {
      fun <- function(a, b) {}
      body(fun) <- formula[[length(formula)]]
      result <- NULL
      for (a in 1:30) {
        for(b in 1:30) {
          result = c(result, fun(a, b))
        }
      }
      return(result)
    }
    
    # test
    result <- foo()
    

    【讨论】:

    • 完美的!谢谢你!
    【解决方案2】:

    我喜欢 G. Grothendieck 提供的解决方案。这是执行此操作的另一种方法,您可以让foo()采用公式的字符表示,并使用as.function()

    foo <- function(f) as.function(alist(a=,b=,eval(parse(text=f))))
    a=1:5
    b=1:5
    f = "(a-b)*a/b"
    result = apply(expand.grid(a,b),1,(x) foo(f)(x[1],x[2]))
    

    输出:

     [1]  0.0000000 -0.5000000 -0.6666667 -0.7500000 -0.8000000  2.0000000  0.0000000
     [8] -0.6666667 -1.0000000 -1.2000000  6.0000000  1.5000000  0.0000000 -0.7500000
    [15] -1.2000000 12.0000000  4.0000000  1.3333333  0.0000000 -0.8000000 20.0000000
    [22]  7.5000000  3.3333333  1.2500000  0.0000000
    

    【讨论】:

    • 太好了,谢谢!
    【解决方案3】:

    使用alistas.function,以及outer而不是双重for循环。

    foo1 <- function(fo=y ~ a - b, a=1:30, b=1:30) {
      f <- as.function(c(alist(b=, a=), fo[[3]]))
      outer(b, a, f) |> as.vector()
    }
    
    ## test
    result <- foo()  ## G. Grothendieck's
    result1 <- foo1()
    
    stopifnot(all.equal(result, result1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多