我有一些匿名的调查数据:
df <- structure(list(User = c("user1", "user2", "user3", "user4", "user5",
"user6", "user7", "user8", "user9", "user10", "user11", "user12",
"user13", "user14"), Q1 = c(0, 3, 5, 0, 6, 5, 1, 4, 6, 4, 5,
0, 0, 0), Q2 = c(0, 6, 4, 0, 4, 5, 0, 4, 6, 5, 5, 5, 0, 4), Q3 = c(0,
4, 5, 3, 4, 5, 0, 4, 4, 5, 5, 0, 0, 0), Q4 = c(5L, 6L, 6L, 7L,
6L, 6L, 6L, 4L, 3L, 4L, 6L, 5L, 3L, 6L), Q5 = c(7L, 5L, 6L, 7L,
5L, 5L, 7L, 4L, 4L, 6L, 6L, 6L, 6L, 6L), Q6 = c(6, 5, 7, 7, 7,
6, 7, 6, 0, 5, 4, 7, 3, 6), Q7 = c(6L, 7L, 7L, 7L, 6L, 6L, 7L,
4L, 5L, 6L, 6L, 6L, 7L, 6L), Q8 = c(1, 4, 6, 3, 4, 6, 3, 4, 4,
5, 4, 0, 1, 3), Q9 = c(3, 3, 4, 0, 4, 5, 1, 4, 3, 5, 7, 4, 0,
0), Q10 = c(3, 3, 3, 0, 5, 5, 3, 4, 5, 6, 7, 5, 0, 4), Q11 = c(3,
4, 5, 0, 4, 5, 5, 4, 3, 5, 6, 4, 0, 0), Q12 = c(6, 6, 5, 0, 4,
0, 7, 4, 5, 3, 0, 6, 5, 5)), .Names = c("User", "Q1", "Q2", "Q3",
"Q4", "Q5", "Q6", "Q7", "Q8", "Q9", "Q10", "Q11", "Q12"), row.names = c(NA,
-14L), class = "data.frame")
数据框看起来像这样 - 值代表1-7级的响应:
User Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8 Q9 Q10 Q11 Q12
1 user1 0 0 0 5 7 6 6 1 3 3 3 6
2 user2 3 6 4 6 5 5 7 4 3 3 4 6
3 user3 5 4 5 6 6 7 7 6 4 3 5 5
4 user4 0 0 3 7 7 7 7 3 0 0 0 0
5 user5 6 4 4 6 5 7 6 4 4 5 4 4
6 user6 5 5 5 6 5 6 6 6 5 5 5 0
7 user7 1 0 0 6 7 7 7 3 1 3 5 7
8 user8 4 4 4 4 4 6 4 4 4 4 4 4
9 user9 6 6 4 3 4 0 5 4 3 5 3 5
10 user10 4 5 5 4 6 5 6 5 5 6 5 3
11 user11 5 5 5 6 6 4 6 4 7 7 6 0
12 user12 0 5 0 5 6 7 6 0 4 5 4 6
13 user13 0 0 0 3 6 3 7 1 0 0 0 5
14 user14 0 4 0 6 6 6 6 3 0 4 0 5
我想得到每个问题的答案数。
换句话说,结果;
基本上,结果表看起来像这样:
Question count1 count2 count3 count4 count5 count6 count7
Q1 1 0 1 2 3 1 0
Q2 0 0 0 4 4 2 0
Q3 .... .... ....
如何在R中完成此操作?可能正在使用我猜的reshape2
包?
答案 0 :(得分:5)
reshape2
主要由tidyr
替换。这是使用dplyr
和tidyr
library(dplyr)
library(tidyr)
df %>%
gather(question, response, Q1:Q12) %>%
count(question, response) %>%
spread(response, n, fill = 0)
结果:
# A tibble: 12 x 8
question `0` `1` `3` `4` `5` `6` `7`
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Q1 5.00 1.00 1.00 2.00 3.00 2.00 0
2 Q10 2.00 0 4.00 2.00 4.00 1.00 1.00
3 Q11 3.00 0 2.00 4.00 4.00 1.00 0
4 Q12 3.00 0 1.00 2.00 4.00 3.00 1.00
5 Q2 4.00 0 0 4.00 4.00 2.00 0
6 Q3 5.00 0 1.00 4.00 4.00 0 0
7 Q4 0 0 2.00 2.00 2.00 7.00 1.00
8 Q5 0 0 0 2.00 3.00 6.00 3.00
9 Q6 1.00 0 1.00 1.00 2.00 4.00 5.00
10 Q7 0 0 0 1.00 1.00 7.00 5.00
11 Q8 1.00 2.00 3.00 5.00 1.00 2.00 0
12 Q9 3.00 1.00 3.00 4.00 2.00 0 1.00