【发布时间】:2019-11-14 17:02:29
【问题描述】:
我有一个表单数据框,其中包含相同 IDs 和 dates 的多个条目。
我需要将此数据集分组为一行,但我在使用收集、传播和分组时遇到了一些问题。
# surveys dataset
user_id <- c(100, 100, 100, 200, 200, 200)
int_id <- c(1000, 1000, 1000, 2000, 2000, 2000)
fech <- c('01/01/2019', '01/01/2019','01/01/2019','02/01/2019','02/01/2019','02/01/2019')
order <- c(1,2,3,1,2,3)
questions <- c('question1','question2','question3','question1','question2','question3')
answers <- c('answ1','answ2','answ3','answ1','answ2','answ3')
survey.data <- data.frame(user_id, int_id, fech, order, questions,answers)
> survey.data
user_id int_id fech order questions answers
1 100 1000 01/01/2019 1 question1 answ1
2 100 1000 01/01/2019 2 question2 answ2
3 100 1000 01/01/2019 3 question3 answ3
4 200 2000 02/01/2019 1 question1 answ1
5 200 2000 02/01/2019 2 question2 answ2
6 200 2000 02/01/2019 3 question3 answ3
我使用 spread 将一些列转换为行:
survey.data %>%
spread(key= questions, value=answers) %>%
group_by(user_id,int_id, fech) %>%
select(-order)
并获得以下信息:
# A tibble: 6 x 6
user_id int_id fech question1 question2 question3
* <dbl> <dbl> <fctr> <fctr> <fctr> <fctr>
1 100 1000 01/01/2019 answ1 NA NA
2 100 1000 01/01/2019 NA answ2 NA
3 100 1000 01/01/2019 NA NA answ3
4 200 2000 02/01/2019 answ1 NA NA
5 200 2000 02/01/2019 NA answ2 NA
6 200 2000 02/01/2019 NA NA answ3
我尝试对生成的数据集进行分组,但总是得到 6 行而不是 2 行。
我预计会出现以下情况:
user_id int_id fech question1 question2 question3
100 1000 01/01/2019 answ1 answ2 answ3
200 2000 02/01/2019 answ1 answ2 answ3
我的问题和this很相似!
但我不知道如何使用 make it。
【问题讨论】:
-
我认为您需要先进行分组,然后再进行传播。