繁体   English   中英

通过公式在R中起作用?

[英]Pass formula to function in R?

任何有关这方面的帮助将非常感激。 我正在使用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

或类似的东西。 问题是我无法弄清楚如何使用变量名将公式传递给函数。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM