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

How to apply for loop function into crosstab making in 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_1 D E
Somewhat worried 19.16831 47.79164
Not too worried 80.83169 29.87610
Not at all worried 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)
}
i D E
Q2_1 100.0000 100.0000
n 2.5923 4.5441

我有这个错误的交叉表列名“Q2_1”移动到第一行并创建一个名为“i”的列。我的目标是从 Q2_1、Q2_2 等列创建多个交叉表。有谁知道如何解决这个问题?

第一次使用栈溢出。希望格式清晰正确。

你可以试试:

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)
}

这个returns

# 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