Aggregate by multiple columns and reshape from long to wide

后端 未结 4 1738
梦如初夏
梦如初夏 2020-12-22 11:50

There are some questions similar to this topic on SO but not exactly like my usecase. I have a dataset where the columns are laid out as shown below

     Id          


        
4条回答
  •  臣服心动
    2020-12-22 12:54

    Use dcast or even acast from reshape2() package

    dcast(dat,Id~Description,mean)
       Id   Cat   Dog
     1 10 14.25 14.25
     2 11 15.25 15.25
    

    Base R might be abit longer:

     reshape(aggregate(.~Id+Description,dat,mean),direction = "wide",v.names  = "Value",idvar = "Id",timevar = "Description")
      Id Value.Cat Value.Dog
    1 10     14.25     14.25
    2 11     15.25     15.25
    

提交回复
热议问题