如何将循环函数应用到r中的交叉表制作中


test1 <- structure(list(weight = c(0.2158, 0.799, 0.611, 0.4969, 0.3469, 
1.0107, 0.6946, 0.9415, 1.4008, 0.6192), Q2_1 = structure(c(4, 
4, 2, 2, 3, 3, 3, 2, 3, 2), label = "How worried, if at all, are you about each of the following? - You or someone in your family will get sick with COVID-19", format.spss = "F40.0", display_width = 5L, labels = c(Skipped = -1, 
`Very worried` = 1, `Somewhat worried` = 2, `Not too worried` = 3, 
`Not at all worried` = 4), class = c("haven_labelled", "vctrs_vctr", 
"double")), Q2_2 = structure(c(3, 4, 2, 4, 3, 3, 4, 2, 3, 4), label = "How worried, if at all, are you about each of the following? - You might experience serious side effects from the COVID-19 vaccine", format.spss = "F40.0", display_width = 5L, labels = c(Skipped = -1, 
`Very worried` = 1, `Somewhat worried` = 2, `Not too worried` = 3, 
`Not at all worried` = 4), class = c("haven_labelled", "vctrs_vctr", 
"double")), group = c("E", "E", "E", "D", "E", "E", "D", "E", 
"D", "E")), row.names = c(NA, -10L), class = "data.frame")

这是我想做的目标交叉表之一。

library(pollster)
crosstab(df = test1 , x = Q2_1, y = group, weight = weight,pct_type = "column")
<表类>Q2_1DEtbody><<tr>有些担心道明>47.79164不太担心80.8316929.87610根本不担心0.0000022.33226n2.592304.54410

你可以试试:

library(pollster)
library(rlang)
for (i in colnames(test1)[2:3]) {
table <- crosstab(
df = test1, 
x = !!sym(i), 
y = group, 
weight = weight, 
pct_type = "column")
print(table)
}

这返回

# A tibble: 4 x 3
Q2_1                   D     E
<chr>              <dbl> <dbl>
1 Somewhat worried   19.2  47.8 
2 Not too worried    80.8  29.9 
3 Not at all worried  0    22.3 
4 n                   2.59  4.54
# A tibble: 4 x 3
Q2_2                   D     E
<chr>              <dbl> <dbl>
1 Somewhat worried    0    34.2 
2 Not too worried    54.0  34.6 
3 Not at all worried 46.0  31.2 
4 n                   2.59  4.54

相关内容

  • 没有找到相关文章

最新更新