我使用Google表单进行了调查。我将响应数据集下载为电子表格,但不幸的是,当涉及到多个选择,多个回答响应时,数据看起来像这样:
Q1 Q2 Q3
1 "A, B ,C" S
2 "C, D" T
1 "A, C, E" U
3 "D" V
2 "B, E" Z
我希望以类似下面的形式提供它:
Q1 Q2 Q2A Q2B Q2C Q2D Q2E Q3
1 "A, B, C" 1 1 1 0 0 S
2 "C, D" 0 0 1 1 0 T
1 "A, C, E" 1 0 1 0 1 U
3 "D" 0 0 0 1 0 V
2 "B, E" 0 1 0 0 1 Z
有一种聪明的方法吗?我有多个选择,多个答案问题和超过250个受访者,所以我希望能够轻松完成。
提前致谢。
答案 0 :(得分:1)
使用dplyr
和tidyr
个包:
dat %>%
separate(Q2, paste0("v", 1:5), remove=F) %>%
gather(q2, val, v1:v5) %>%
na.exclude %>%
mutate(val=paste0("Q2", val), q2=1) %>%
spread(val, q2) %>%
select(Q1:Q2, Q2A:Q2E, Q3) %>%
mutate_at(vars(Q2A:Q2E), .funs=funs(replace(., is.na(.), 0)))
Q1 Q2 Q2A Q2B Q2C Q2D Q2E Q3
1 1 A, B ,C 1 1 1 0 0 S
2 1 A, C, E 1 0 1 0 1 U
3 2 B, E 0 1 0 0 1 Z
4 2 C, D 0 0 1 1 0 T
5 3 D 0 0 0 1 0 V
输入数据:
dat <- structure(list(Q1 = c(1L, 2L, 1L, 3L, 2L), Q2 = structure(c(1L,
4L, 2L, 5L, 3L), .Label = c("A, B ,C", "A, C, E", "B, E", "C, D",
"D"), class = "factor"), Q3 = structure(1:5, .Label = c("S",
"T", "U", "V", "Z"), class = "factor")), .Names = c("Q1", "Q2",
"Q3"), class = "data.frame", row.names = c(NA, -5L))