Gather multiple sets of columns

后端 未结 5 875
耶瑟儿~
耶瑟儿~ 2020-11-22 03:01

I have data from an online survey where respondents go through a loop of questions 1-3 times. The survey software (Qualtrics) records this data in multiple columns—that is,

5条回答
  •  [愿得一人]
    2020-11-22 03:37

    In case you are like me, and cannot work out how to use "regular expression with capturing groups" for extract, the following code replicates the extract(...) line in Hadleys' answer:

    df %>% 
        gather(question_number, value, starts_with("Q3.")) %>%
        mutate(loop_number = str_sub(question_number,-2,-2), question_number = str_sub(question_number,1,4)) %>%
        select(id, time, loop_number, question_number, value) %>% 
        spread(key = question_number, value = value)
    

    The problem here is that the initial gather forms a key column that is actually a combination of two keys. I chose to use mutate in my original solution in the comments to split this column into two columns with equivalent info, a loop_number column and a question_number column. spread can then be used to transform the long form data, which are key value pairs (question_number, value) to wide form data.

提交回复
热议问题