How do I use spread and group_by on a single row dataset

末鹿安然 提交于 2019-12-11 13:27:10

问题


I have a form dataframe that has multiple entries for same IDs and dates. I need to group this dataset to a single row, but I have some problems with the use of gather, spread and group.

# 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

I use spread to take some columns to rows:

survey.data %>% 
  spread(key= questions, value=answers) %>%
  group_by(user_id,int_id, fech) %>% 
  select(-order) 

And get the following:

# 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

I tried to group the resulting dataset, but always get 6 rows instead of 2.

I expected the following:

user_id int_id  fech        question1 question2 question3
 100   1000     01/01/2019     answ1     answ2     answ3
 200   2000     02/01/2019     answ1     answ2     answ3

My question is very similar to this!

But I can´t figure out how to use make it.


回答1:


I think you need to remove order before grouping:

survey.data %>% 
  select(-order) %>% 
  # group_by(user_id, int_id, fech) %>% # as pointed out, unnecessary
  spread(questions, answers)

Result:

# A tibble: 2 x 6
# Groups:   user_id, int_id, fech [2]
  user_id int_id fech       question1 question2 question3
    <int>  <int> <chr>      <chr>     <chr>     <chr>    
1     100   1000 01/01/2019 answ1     answ2     answ3    
2     200   2000 02/01/2019 answ1     answ2     answ3 



回答2:


I found (i think) another possible solution:

survey.data %>% 
  select(-order) %>% 
  dcast(... ~ questions)
´´´


来源:https://stackoverflow.com/questions/56879714/how-do-i-use-spread-and-group-by-on-a-single-row-dataset

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!