Reshape Data Long to Wide - understanding reshape parameters

前端 未结 3 1175
遥遥无期
遥遥无期 2020-12-04 00:44

I have a long format dataframe dogs that I\'m trying to reformat to wide using the reshape() function. It currently looks like so:

dogid  month  year  traini         


        
3条回答
  •  [愿得一人]
    2020-12-04 01:13

    You can use the function dcast from package reshape2. It's easier to understand. The left side of the formula is the one that stays long, while the right side is the one that goes wide.

    The fun.aggregate is the function to apply in case that there is more than 1 number per case. If you're sure you don't have repeated cases, you can use mean or sum

    dcast(data, formula= dogid + home + school ~ month + year + trainingtype,
    value.var = 'timeincomp',
    fun.aggregate = sum)
    

    I hope it works:

      dogid home school 1_2014_1 2_2014_1 12_2015_2
    1 12345    1      1      340      360         0
    2 31323    7      3      500      520       440
    

提交回复
热议问题