如何在R中将公式传递给函数?

11
任何关于这个的帮助都将不胜感激。我正在使用Lumley survey包并尝试简化我的代码,但遇到了一些小问题。
在我的代码中,从该包中调用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))
}

这个方法有效,当我要提取出第一个分类的平均值和标准误时,我使用以下代码:

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

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

2个回答

14
您可以使用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

查看这个答案,以获取有关以编程方式创建公式对象的更多详细信息。

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

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

0

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 ) )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接