简体   繁体   中英

Can I get unwtd.count included when running the svymean from the R Survey package?

I've written an R script to loop through a bunch of variables in a survey and output weighted values, CVs, CIs etc. I would like it to also output the unweighted observations count.

I know it's a bit of a lazy question because I can calculate unweighted counts on my own and join them back in. I'm just trying to replicate a stata script that would return 'obs'

svy:tab jdvariable, per cv ci obs column format(%14.4g)

This is my calculated values table:

myresult_year_calc <- svyby(make.formula(newmetricname), # variable to pass to function
by = ~year,  # grouping
design = subset(csurvey, geoname %in% jv_geo), # design object with subset definition
vartype = c("ci","cvpct"), # report variation as ci, and cv percentage
na.rm.all=TRUE,
FUN = svymean # specify function from survey package
)

By using unwtd.count instead of FUN, I get the counts I want.

myresult_year_obs <- svyby(make.formula(newmetricname), # variable to pass to function
by = ~year,  # grouping
design = subset(csurvey, geoname %in% jv_geo), # design object with subset definition
vartype = c("ci","cvpct"), # report variation as ci, and cv percentage
na.rm.all=TRUE,
unwtd.count
)

Honestly in writing this question I made it 98% through a solution, but I'll ask anyway in case someone knows a more efficient way.

myresult_year_calc and myresult_year_obs both return what I expect, and if I use merge(myresult_year_calc, myresult_year_obs by"year") I get the table I want. This actually just gives me one count, per year in this example instead of one count for 'Yes' responses and one count for 'No'.

Is there any way to get both means and unweighted counts with a single command?

I figured this out by creating a second dsgn function where weights = ~0. When I ran svyby using the svytotal function with the unweighted design it followed the formula.

dsgn2 <- svydesign(ids = ~0, weights = ~0, data = data, na.rm = T)

unweighted_n <- svyby(~interaction(group1,group2), ~as.factor(mean_rating), design = dsgn2, FUN = svytotal, na.rm = T)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM