Complicated reshaping

后端 未结 8 1421
南方客
南方客 2020-12-25 14:01

I want to reshape my dataframe from long to wide format and I loose some data that I\'d like to keep. For the following example:

df <- data.frame(Par1 =          


        
相关标签:
8条回答
  • 2020-12-25 14:53

    One Step solution combining reshape::cast with plyr::ddply

    cast(Par1 + Par2 + ParD ~ Type, data = ddply(df, .(Par1, Par2), transform, 
      ParD = paste(ParD, collapse = "_")), fun  = c(mean, length))
    

    NOTE that the dcast function in reshape2 does not allow multiple aggregate functions to be passed, while the cast function in reshape does.

    0 讨论(0)
  • 2020-12-25 14:56

    Solution in 2 steps using ddply ( i am not happy with , but I get the result)

    dat <- ddply(df,.(Par1,Par2),function(x){
      data.frame(ParD=paste(paste(x$ParD),collapse='_'),
                 Num.pre =length(x$Type[x$Type =='pre']),
                 Num.post = length(x$Type[x$Type =='post']))
    })
    
    merge(dfw,dat)
     Par1 Par2 post pre        ParD Num.pre Num.post
    1    A    D  2.0   1     foo_bar       1        1
    2    B    E  4.0   3     baz_qux       1        1
    3    C    F  6.5   5 bla_xyz_meh       1        2
    
    0 讨论(0)
提交回复
热议问题