簡體   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