Reputation: 95
I need to create one way frequency table. The tables have to include the proportions for variables.
Using prop.table(svytable()), I can extract proportions for one variable at a time.
library(survey)
round(prop.table(svytable(~varA,design=designA))*100,digits=2)
However, I need codes that join each output for each variable into one single table. I tried the below but it is not a table.
c(output1,output2...)
For example, the expected output for VarA and VarB with 2 levels
|Var Name|Proportion|
| A| |
|Yes | 50.0|
|No | 50.0|
| B| |
|Yes | 20.0|
|No | 80.0|
The actual output using c() is just a vector.
Yes No Yes No
50 50 20 80
Sample dput(data)
structure(list(psu = structure(c(1, 1, 2, 2), format.sas = "BEST"),
strata = structure(c(1, 2, 3, 4), format.sas = "BEST"), wt =structure(c(1.7,
0.8, 1.2, 0.3), format.sas = "BEST"), residence = structure(c("Urban",
"Rural", "Urban", "Urban"), format.sas = "$CHAR"), income = structure(c("High", "Low", "Low", "High"), format.sas = "$CHAR")),
label = "TEST", row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame"))
Example on how to extract proportion for single variable.
library(survey)
testdesign<- svydesign(id=test$psu, strata=test$strata, weight=test$wt, nest=TRUE, data=test)
a=round(prop.table(svytable(~residence,design=testdesign))*100,digits=2)
Upvotes: 4
Views: 3476
Reputation: 388907
Is this what you are trying to achieve ?
library(survey)
prop.table(svytable(~residence + income,design=testdesign), 1) * 100
# income
#residence High Low
# Rural 0.0 100.0
# Urban 62.5 37.5
If we want to combine two outputs we need same column names which can be done via setNames
output1 <- round(prop.table(svytable(~residence,design=testdesign))*100,digits=2)
output2 <- round(prop.table(svytable(~income,design=testdesign))*100,digits=2)
rbind(setNames(as.data.frame(output1), c("Var1", "Freq")),
setNames(as.data.frame(output2), c("Var1", "Freq")))
# Var1 Freq
#1 Rural 20
#2 Urban 80
#3 High 50
#4 Low 50
Upvotes: 3