Execute a formula for a function in R?

Any help with this would be really appreciated. I am using the Lumley poll package and am trying to simplify my code but hit it a bit.

The svymean function from the package in my code is called like this, the first argument is a formula indicating which variables I want, and the second argument is a dataset:

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

      

I'm trying to create a function that will pull out the means (proportions) and standard errors for categorical variables, so I ran the following function:

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

      

This works, so when I pull out the middle and one of my first category, for example, I use:

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

      

What I would like to do is simplify this to something significantly shorter, where I may only have to write:

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

      

Or something like that. The problem is I can't figure out how to pass the formula to the function using the variable name.

+3


source to share


2 answers


You can use reformulate

to build a formula and call it svymean

in your function. Use ...

to pass na.rm

or other arguments tosvymean

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

      

See this answer for more details on creating formula objects programmatically



Or you can pass a formula object inside a function.

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

      

+8


source


Functions coef

and SE

can make your life easier.



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

      

0


source







All Articles