0

在 R 中,一项看似简单的任务已被证明非常困难。我正在处理包含命题的调查数据,这些命题要求受访者在 7 点李克特量表上表明他们同意或不同意的程度。我正在尝试创建频率表(参见下面的表 1),以显示每个性别/年龄组类别中选择强烈同意、略微同意、同意、中立等的受访者比例,以回应每个提议。

如何从表 2 创建表 1(这是我在 R 中设置当前数据框的方式)?在表 2 中,标题为 Q31、Q32、Q33 和 Q34 的列分别是独立的命题,单元格中的值是李克特量表上 7 个选项的数字代码。

表格1

性别 年龄阶层 问题 非常同意
1 30 - 39 31 0.21
2 30 - 39 31 0.48
1 40 - 49 31 0.12
2 40 - 49 31 0.65

表 2

性别 年龄阶层 Q31 Q32 Q33 Q34
1 30 - 39 1 7 1 5
2 30 - 39 3 5 2 6
1 40 - 49 4 6 3 2
2 40 - 49 2 2 4 2

对任何建议持开放态度,因为我已经反对这个问题太久了!谢谢!

4

1 回答 1

0

第一步可能是将您的宽数据转换为长格式(年龄,性别,然后一列用于问题类型,一列用于该问题的答案)。使用这种长格式或整齐的数据,您可以轻松按问题、年龄和性别分组,并计算每个答案的比例。

代码

library(tidyverse)

df %>% 
  pivot_longer(cols = -c(Sex, `Age Group`),
               names_to = "Question",
               values_to = "Value") %>%
  group_by(Question, Sex, `Age Group`) %>%
  summarise(`Strongly Agree` = sum(Value == 7)/n(),
            `Slightly Agree` = sum(Value == 6)/n(),
            Agree = sum(Value == 5)/n(),
            Neutral = sum(Value == 4)/n(),
            Disagree = sum(Value == 3)/n(),
            `Slightly Disagree` = sum(Value == 2)/n(),
            `Strongly Disagree` = sum(Value == 1)/n()) 

输出

# A tibble: 16 x 10
# Groups:   Question, Sex [8]
   Question   Sex `Age Group` `Strongly Agree` `Slightly Agree` Agree Neutral Disagree `Slightly Disagree` `Strongly Disagree`
   <chr>    <int> <fct>                  <dbl>            <dbl> <dbl>   <dbl>    <dbl>               <dbl>               <dbl>
 1 Q31          1 30-39                      0                0     0       0        0                   0                   1
 2 Q31          1 40-49                      0                0     0       1        0                   0                   0
 3 Q31          2 30-39                      0                0     0       0        1                   0                   0
 4 Q31          2 40-49                      0                0     0       0        0                   1                   0

注意:在您的示例表 2 中,每个性别 x 年龄组合存在一次,因此您示例的比例为 0 或 1。

数据

df <- structure(list(Sex = c(1L, 2L, 1L, 2L), `Age Group` = structure(c(1L, 
1L, 2L, 2L), .Label = c("30-39", "40-49"), class = "factor"), 
    Q31 = c(1L, 3L, 4L, 2L), Q32 = c(7L, 5L, 6L, 2L), Q33 = 1:4, 
    Q34 = c(5L, 6L, 2L, 2L)), class = "data.frame", row.names = c(NA, 
-4L))
于 2021-04-05T20:14:26.307 回答