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