Gather multiple sets of columns

后端 未结 5 977
耶瑟儿~
耶瑟儿~ 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:49

    This approach seems pretty natural to me:

    df %>%
      gather(key, value, -id, -time) %>%
      extract(key, c("question", "loop_number"), "(Q.\\..)\\.(.)") %>%
      spread(question, value)
    

    First gather all question columns, use extract() to separate into question and loop_number, then spread() question back into the columns.

    #>    id       time loop_number         Q3.2        Q3.3
    #> 1   1 2009-01-01           1  0.142259203 -0.35842736
    #> 2   1 2009-01-01           2  0.061034802  0.79354061
    #> 3   1 2009-01-01           3 -0.525686204 -0.67456611
    #> 4   2 2009-01-02           1 -1.044461185 -1.19662936
    #> 5   2 2009-01-02           2  0.393808163  0.42384717
    

提交回复
热议问题