【问题标题】:Pass formula to function in R?将公式传递给 R 函数?
【发布时间】:2013-01-18 16:19:32
【问题描述】:

对此的任何帮助将不胜感激。我正在使用 Lumley 调查包并尝试简化我的代码,但遇到了一点小问题。

包中的svymean函数在我的代码中调用如下,其中第一个参数是一个公式,表示我想要哪些变量,第二个参数是那个数据集:

svymean(~hq_ehla, FraSvy, na.rm=TRUE)

我正在尝试创建一个函数来提取分类变量的平均值(比例)和标准误差,因此我创建了以下函数:

stats <- function(repstat, num) {
    estmean <- as.numeric(round(100 * repstat[num], digits=0))
    estse <- round(100 * sqrt(attributes(repstat)$var[num,num]), digits=1)
    return(list(mean=estmean, se=estse))
}

这行得通,所以当我提取我的第一个类别的均值和 se 时,例如,我使用:

stats(svymean(~hq_ehla, FraSvy, na.rm=TRUE), 1)$mean
stats(svymean(~hq_ehla, FraSvy, na.rm=TRUE), 1)$se

我想做的就是把它简化为更短的东西,也许我只需要写:

stats(FraSvy, "hq_ehla", 1)$mean

或者类似的东西。问题是我不知道如何使用变量名将公式传递给函数。

【问题讨论】:

    标签: r function formula survey


    【解决方案1】:

    您可以使用reformulate 来构造您的公式并在您的函数中调用svymean。使用...na.rm 或其他参数传递给svymean

    stats <- function(terms, data,  num, ...) {
      .formula <- reformulate(terms)
      repstat <- svymean(.formula, data, ...)
      estmean <- as.numeric(round(100 * repstat[num], digits=0))
      estse <- round(100 * sqrt(attributes(repstat)$var[num,num]), digits=1)
      return(list(mean=estmean, se=estse))
    }
    
    stats(data = FraSvy, terms = "hq_ehla", 1, na.rm = TRUE)$mean
    

    查看this answer,了解有关以编程方式创建公式对象的更多详细信息

    或者,您可以在函数中传递一个公式对象。

    stats2 <- function(formula, data,  num, ...) {
    
      repstat <- svymean(formula, data, ...)
      estmean <- as.numeric(round(100 * repstat[num], digits=0))
      estse <- round(100 * sqrt(attributes(repstat)$var[num,num]), digits=1)
      return(list(mean=estmean, se=estse))
    }
    
    
    stats2(data = FraSvy, formula = ~hq_ehla, 1, na.rm = TRUE)$mean
    

    【讨论】:

      【解决方案2】:

      coefSE 函数可能会让您的生活更轻松..

      # construct a function that takes the equation part of svymean as a string
      # instead of as a formula.  everything else gets passed in the same
      # as seen by the `...`
      fun <- function( var , ... ) svymean( reformulate( var ) , ... )
      
      # test it out.
      result <- fun( "hq_ehla" , FraSvy , na.rm = TRUE )
      
      # print the results to the screen
      result
      
      # also your components
      coef( result )
      SE( result )
      
      # and round it
      round( 100 * coef( result ) )
      round( 100 * SE( result ) )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-09
        • 2020-03-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多