Reshape wide format, to multi-column long format

前端 未结 4 1637
一生所求
一生所求 2020-12-14 10:01

I want to reshape a wide format dataset that has multiple tests which are measured at 3 time points:

   ID   Test Year   Fall Spring Winter
    1   1   2008          


        
4条回答
  •  眼角桃花
    2020-12-14 10:09

    Base reshape function alternative method is below. Though this required using reshape twice, there might be a simpler way.

    Assuming your dataset is called df1

    tmp <- reshape(df1,idvar=c("ID","Year"),timevar="Test",direction="wide")
    result <- reshape(
       tmp,
       idvar=c("ID","Year"),
       varying=list(3:5,6:8),
       v.names=c("Test1","Test2"),
       times=c("Fall","Spring","Winter"),
       direction="long"
    )
    

    Which gives:

    > result
                  ID Year   time Test1 Test2
    1.2008.Fall    1 2008   Fall    15    22
    1.2009.Fall    1 2009   Fall    12    10
    2.2008.Fall    2 2008   Fall    12    13
    2.2009.Fall    2 2009   Fall    16    23
    3.2008.Fall    3 2008   Fall    11    17
    3.2009.Fall    3 2009   Fall    13    14
    1.2008.Spring  1 2008 Spring    16    22
    1.2009.Spring  1 2009 Spring    13    14
    2.2008.Spring  2 2008 Spring    13    11
    2.2009.Spring  2 2009 Spring    14    20
    3.2008.Spring  3 2008 Spring    12    12
    3.2009.Spring  3 2009 Spring    11     9
    1.2008.Winter  1 2008 Winter    19    24
    1.2009.Winter  1 2009 Winter    27    20
    2.2008.Winter  2 2008 Winter    25    29
    2.2009.Winter  2 2009 Winter    21    26
    3.2008.Winter  3 2008 Winter    22    23
    3.2009.Winter  3 2009 Winter    27    31
    

提交回复
热议问题