I'm new to R. Thank you for your patience. I'm working with the survey package.
Background: I'm writing a function that loops through combinations of predictor and outcome variables (i.e., svyglm(outcome~predictor)
) in a complex survey to output crude prevalence ratios. For each outcome/predictor combination, I want to first relevel the predictor within the survey design object to ensure the output ratios are all > 1.
Specific problem: Given the survey design object name, column name and reference level as strings, how do I tell R I want said column releveled.
prams16 is the name of the survey design object which includes a list of 9 items, variables is the analytic dataset (data frame) within the survey design object and mrace is a column in the variables DF.
These work:
prams16$variables$mrace <- relevel(prams16$variables$mrace, ref="White")
prams16[["variables"]]["mrace"] <- relevel(prams16$variables$mrace, ref="White")
However, when I try to construct references to prams16$variables$mrace
or prams16[["variables"]]["mrace"]
with strings, nothing seems to work.
Thanks!
EDIT: Requested reproducible example of problem.
myPredictor <- as.factor(c("Red","White","Black","Red","Green","Black","White","Black","Red","Green","Black"))
myOutcome <- c(1,0,1,0,1,0,1,0,1,0,1)
myDF <- tibble(myPredictor, myOutcome)
myOtherStuff <- c("etc","etc")
myObj <- list(myDF=myDF,myOtherStuff=myOtherStuff)
#These work...
myObj$myDF$myPredictor <- relevel(myObj$myDF$myPredictor, ref="White")
str(myObj$myDF$myPredictor) #"White" is now the referent level
myObj[["myDF"]]["myPredictor"] <- relevel(myObj$myDF$myPredictor, ref="Red")
str(myObj$myDF$myPredictor) #"Red" is now the referent level
#How to construct relevel assignment statement from strings?
anObj <- "myObj"
aPredictor <- "myPredictor"
aRef <- "Green"
#Produces error
as.name(paste0(anObj,"$myDF$",aPredictor)) <- relevel(as.name(paste0(anObj,"$myDF$",aPredictor)), ref=aRef)