Reputation: 71
I am trying unsuccessfully to create an R survey design object (from the R survey
package) using arguments supplied within a new function I am creating. This new function seeks to account for the complex survey design in computing prevalence estimates derived as part of the function. I can successfully get the new function to work if I supply the survey design object as an argument in my function; I would however prefer not to do that as it complicates things. Below is sample data, the function I am trying to create and my unsuccessful attempts at creating the survey design object within the new function. For the examples below, the dataframe is n
, the survey design object I wish to create in the new function is svyob
, the weight variable is wt
, the id variable is psu
, and the strata variable is stratum
. The desired structure of my new function, along with default values, is as follows (note that my outcome will be derived within the function. But for purposes of illustration, assume it is the distribution of sex):
prev = function(data, wt, psu = 1, stratum = NULL) {
#Step1: Derive outcome of interest from dataframe (not shown)
#Step2: Create survey design object
svyobj = survey::svydesign(data = n, weights =~ wt[1], id =~ psu[1], strata =~ stratum[1], nest = T)
#Step 3: Generate summary estimates
svymean(~outcome, svyobj, svyobj, na.rm = T)
}
Data:
structure(list(wt = 1365.61822580832, psu = 600815, strata = structure(9L, .Label = c("101",
"102", "103", "104", "111", "112", "113", "114", "201", "203",
"204", "211", "212", "213", "214"), class = "factor"), age = 1,
sex = 1, school = 1), row.names = 50L, class = "data.frame")
*I have been unsuccessful thus far with supplying the weights variable in step 2 above. I have tried specifying the weight variable as weights = "wt", weights = eval(parse(text = "wt")), weights = eval(quote(wt)), weights = wt[1], etc. All to no avail. Some error statements are below:
weights= as.formula(paste0("~", eval(parse(text = "wt")))) # Error in { : task 1 failed - "(subscript) logical subscript too long"
weights= as.formula(paste0("~", eval(get(wt)))) #Error in get(wt) : object 'wt' not found
I will greatly appreciate any help.
Upvotes: 2
Views: 636
Reputation: 71
I finally got my code working with both of the following (went for #2):
#Using (eval(parse())
svyobject = svydesign(data=n, id= as.formula(paste0("~", eval(parse(text = "psu")))) , strata=as.formula(paste0("~", eval(parse(text = "stratum")))), weights= as.formula(paste0("~", eval(parse(text = "wt")))), nest=TRUE)
#Using (eval(get())
svyobject = svydesign(data=n, id= as.formula(paste0("~", eval(get("psu")))) , strata=as.formula(paste0("~", eval(get("stratum")))), weights= as.formula(paste0("~", eval(get("wt")))), nest=TRUE)
Upvotes: 2