Home > OS >  Pass variable name as argument dynamically on svydesign and dplyr::select functions
Pass variable name as argument dynamically on svydesign and dplyr::select functions

Time:02-08

I'm newbie with R. There is a code like the following, and for that code, variable name wt_itvex_divided_by_4 should be dynamically replaced with wt_itvex_divided_by_3 or wt_itvex_divided_by_2

df_odds_sv <- as_survey(
  svydesign(id = ~psu ID_fam,
            strata = ~kstrata,
            weights = ~wt_itvex_divided_by_4,
            data = data_sd1013
            )) %>%
  dplyr::select(ID, ID_fam, psu, kstrata, wt_itvex_divided_by_4) %>%
  subset(ID %in% df_odds$ID)

To implement dynamical change, I tried something like the following by using temp variable, but it didn't work

temp='wt_itvex_divided_by_3'

df_odds_sv <- as_survey(
  svydesign(id = ~psu ID_fam,
            strata = ~kstrata,
            weights = ~temp,
            data = data_sd1013
            )) %>%
  dplyr::select(ID, ID_fam, psu, kstrata, temp) %>%
  subset(ID %in% df_odds$ID)

Or, by some search on this problem, I saw someone recommended to use get(), so I tried like the following. It didn't create the error but wt_itvex_divided_by_3 column wasn't selected

s<-'wt_itvex_divided_by_3'

df_odds_sv <- as_survey(
  svydesign(id = ~psu ID_fam,
            strata = ~kstrata,
            weights = ~get(s),
            data = data_sd1013
            )) %>%
  dplyr::select(ID, ID_fam, psu, kstrata, get(s)) %>%
  subset(ID %in% df_odds$ID)

Referencing Ronak Shah's answer, I solved the issue by the following code (note that I used arguments differently for svydesign's weights and dplyr::select)

temp='wt_itvex_divided_by_3'

df_odds_sv <- as_survey(
  svydesign(id = ~psu ID_fam,
            strata = ~kstrata,
            weights = ~data_sd1013[[temp]],
            data = data_sd1013
            )) %>%
  dplyr::select(ID, ID_fam, psu, kstrata, temp) %>%
  subset(ID %in% df_odds$ID)

CodePudding user response:

You may try subsetting from the dataframe directly with [[.

Using apistrat data as an example.

library(survey)
library(srvyr)
data(api)

temp= "pw"

dstrat1 <- svydesign(id=~1,strata=~stype, weights= ~apistrat[[temp]],
                     data=apistrat, fpc=~fpc)
  •  Tags:  
  • Related