Home > database >  How to apply for loop function into crosstab making in R
How to apply for loop function into crosstab making in R

Time:10-19

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

This is one of the goal crosstabs I would like to make.

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

I'm trying to make multiple crosstabs by using a loop function.

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

I've got this wrong crosstab the column name "Q2_1" move to the first row and create a column called "i". My goal is to create multiple crosstabs from columns such as Q2_1, Q2_2. Does anyone know how to fix this problem?

This is the first time using stack overflow. Hope the formatting is clear and correct.

CodePudding user response:

You could try:

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

This 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
  • Related