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_1 | D | 乙 |
|---|---|---|
| 有點擔心 | 19.16831 | 47.79164 |
| 不太擔心 | 80.83169 | 29.87610 |
| 一點都不擔心 | 0.00000 | 22.33226 |
| n | 2.59230 | 4.54410 |
我正在嘗試使用回圈函式制作多個交叉表。
for (i in colnames(test1)[2]) {
table1 <- crosstab(df = test1, x = i, y = group, weight = weight,pct_type = "column")
print(table1)
}
| 一世 | D | 乙 |
|---|---|---|
| Q2_1 | 100.0000 | 100.0000 |
| n | 2.5923 | 4.5441 |
我有這個錯誤的交叉表,列名“Q2_1”移到第一行并創建一個名為“i”的列。我的目標是從 Q2_1、Q2_2 等列創建多個交叉表。有誰知道如何解決這個問題?
這是第一次使用堆疊溢位。希望格式清晰正確。
uj5u.com熱心網友回復:
你可以試試:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/322697.html
上一篇:不使用串列突變洗掉重復項
