Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using syvtable in a R function

I would like to create a function which takes an x (character variable) in argument and put it into the svytable() function as part of the formula.

prop <- function(x){
  
  tab <- svytable(~x+group_treatment, dw)
  df <- as.data.frame(cprop(tab))
  df_bis <- reshape(df,idvar = "x",timevar = "group_treatment", direction = "wide")
  df_bis

}

prop("tranche_age")

When I run this code, I get the following error message : "Error in eval(predvars, data, env) : object ‘x’ not found
Called from: eval(predvars, data, env)".

Any idea to solve this issue?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks,

Chloe

>Solution :

You could use reformulate to dynamically create the formula based on the column name passed to your function. Additonally you have to use idvar = x instead of idvar = "x" in reshape().

Using the default example data from ?svytable:

library(survey)
library(questionr)

data(api)

dw <- svydesign(id=~dnum, weights=~pw, data=apiclus1, fpc=~fpc)

prop <- function(x) {
  tab <- svytable(reformulate(c(x, "stype")), dw)
  df <- as.data.frame(cprop(tab))
  df_bis <- reshape(df, idvar = x, timevar = "stype", direction = "wide")
  df_bis
}

prop("sch.wide")
#>   sch.wide     Freq.E    Freq.H Freq.M  Freq.All
#> 1       No   8.333333  21.42857     32  12.56831
#> 2      Yes  91.666667  78.57143     68  87.43169
#> 3    Total 100.000000 100.00000    100 100.00000
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading