Gather multiple sets of columns

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

    With the recent update to melt.data.table, we can now melt multiple columns. With that, we can do:

    require(data.table) ## 1.9.5
    melt(setDT(df), id=1:2, measure=patterns("^Q3.2", "^Q3.3"), 
         value.name=c("Q3.2", "Q3.3"), variable.name="loop_number")
     #    id       time loop_number         Q3.2        Q3.3
     # 1:  1 2009-01-01           1 -0.433978480  0.41227209
     # 2:  2 2009-01-02           1 -0.567995351  0.30701144
     # 3:  3 2009-01-03           1 -0.092041353 -0.96024077
     # 4:  4 2009-01-04           1  1.137433487  0.60603396
     # 5:  5 2009-01-05           1 -1.071498263 -0.01655584
     # 6:  6 2009-01-06           1 -0.048376809  0.55889996
     # 7:  7 2009-01-07           1 -0.007312176  0.69872938
    

    You can get the development version from here.

提交回复
热议问题