Concatenating a column by a group in R

前端 未结 2 423
心在旅途
心在旅途 2020-12-02 02:32

Suppose I\'ve got this employee list:

 Dept Date      Name            
----- --------- --------------- 
   30 07-DEC-02 Raphaely        
   30 18-MAY-03 Khoo         


        
相关标签:
2条回答
  • 2020-12-02 02:59

    Or plyr:

    gr<-read.csv("gr.csv")
    require(plyr)
    merge(gr,ddply(gr,.(Dept),summarise,Emp_List=paste0(Name,collapse="; ")),by="Dept")
    
    Dept      Date      Name          Emp_List
    1    30 07-DEC-02  Raphaely    Raphaely; Khoo
    2    30 18-MAY-03      Khoo    Raphaely; Khoo
    3    40 07-JUN-02    Mavris            Mavris
    4    50 01-MAY-03  Kaufling  Kaufling; Ladwig
    5    50 14-JUL-03    Ladwig  Kaufling; Ladwig
    6    70 07-JUN-02      Baer              Baer
    7    90 13-JAN-01   De Haan     De Haan; King
    8    90 17-JUN-03      King     De Haan; King
    9   100 16-AUG-02    Faviet Faviet; Greenberg
    10  100 17-AUG-02 Greenberg Faviet; Greenberg
    11  110 07-JUN-02     Gietz    Gietz; Higgins
    12  110 07-JUN-02   Higgins    Gietz; Higgins
    
    0 讨论(0)
  • 2020-12-02 03:16

    You can use ave and paste:

    within(mydf, {
      Emp_list <- ave(Name, Dept, FUN = function(x) paste(x, collapse = "; "))
    })
    #   Dept      Date      Name          Emp_list
    # 1    30 07-DEC-02  Raphaely    Raphaely; Khoo
    # 2    30 18-MAY-03      Khoo    Raphaely; Khoo
    # 3    40 07-JUN-02    Mavris            Mavris
    # 4    50 01-MAY-03  Kaufling  Kaufling; Ladwig
    # 5    50 14-JUL-03    Ladwig  Kaufling; Ladwig
    # 6    70 07-JUN-02      Baer              Baer
    # 7    90 13-JAN-01   De Haan     De Haan; King
    # 8    90 17-JUN-03      King     De Haan; King
    # 9   100 16-AUG-02    Faviet Faviet; Greenberg
    # 10  100 17-AUG-02 Greenberg Faviet; Greenberg
    # 11  110 07-JUN-02     Gietz    Gietz; Higgins
    # 12  110 07-JUN-02   Higgins    Gietz; Higgins
    
    0 讨论(0)
提交回复
热议问题