有没有办法可以在 R 中生成下面的交叉表?

问题描述 投票:0回答:1

[SPSS 的 Crostab 输出]

我想用R生成附加的交叉表。目前我使用SPSS。我使用的数据框如下。变量(Maths_Set、Note_Book、School_Bag、Text_Book、Pen)是调查中的多重响应问题,其中受访者可以有 1 个或多个项目。如果编码为 1,则表示受访者拥有该项目,否则编码为 0。交叉表将 Q1 作为行,将性别和项目分组作为列。它在单个单元格中同时生成计数和百分比。

Q1 <- c(5,5,4,1,5,4,3,3,5,2)
Gender <- c(2,2,2,1,2,2,1,2,1,2)
Maths_Set <- c(1,0,1,1,1,1,1,1,0,1)
Note_Book <- c(1,1,0,1,1,1,1,1,1,1)
School_Bag <- c(0,1,1,0,1,1,1,1,1,1)
Text_Book <- c(0,1,0,1,1,1,1,1,1,1)
Pen <- c(0,0,1,1,1,1,1,1,1,1)

df = data.frame(Q1,Gender,Maths_Set,Note_Book,School_Bag,Text_Book,Pen)
df$Q1 <- factor(df$Q1, levels= c(1,2,3,4,5), labels = c("Strongly Dislike", "Dislike", "Neither like or Dislike", "Like", "Strongly Like"))
df$Gender <- factor(df$Gender, levels = c(1,2), labels = c("Boy", "Girl"))
r dataframe validation spss
1个回答
0
投票

您可以使用 gt 进行格式化,使用 dplyr 进行聚合:

st <- df %>% 
  group_by(Q1) %>% 
  summarize(`Actual Base` = n(),
            Boy = sum(Gender == "Boy"),
            Girl = sum(Gender == "Girl"),
            across(-Gender, .fn = sum)) %>% 
  mutate(across(-Q1, .fn = list(freq = ~ .x / sum(.x))))

bt <- gt(st,
   rowname_col = "Q1") %>% 
  grand_summary_rows(fns = list("Actual Base" ~ sum(.)), 
                     side = "top") %>% 
  fmt_percent(columns = ends_with("freq"),
              decimals = 1) %>% 
  tab_spanner("Gender", c("Boy", "Girl")) %>% 
  tab_spanner("School Items", 5:9)

Reduce(\(x, y) x %>%
         cols_merge(starts_with(y), pattern = "{1} ({2})"),
       st %>% select(!ends_with("freq"), -Q1) %>% names(),
       init = bt)

© www.soinside.com 2019 - 2024. All rights reserved.