gpt4 book ai didi

r - 按组连接/粘贴列并添加到原始数据

转载 作者:行者123 更新时间:2023-12-02 05:43:59 26 4
gpt4 key购买 nike

我有一个名称数据框(“Name”),按“Dept”分组:

 Dept Date      Name            
----- --------- ---------------
30 07-DEC-02 Raphaely
30 18-MAY-03 Khoo
40 07-JUN-02 Mavris
50 01-MAY-03 Kaufling
50 14-JUL-03 Ladwig
70 07-JUN-02 Baer
90 13-JAN-01 De Haan
90 17-JUN-03 King
100 16-AUG-02 Faviet
100 17-AUG-02 Greenberg
110 07-JUN-02 Gietz
110 07-JUN-02 Higgins

我想将“名称”列与“部门”连接并将结果添加到原始数据中。所需的结果是“Emp_list”列:

 Dept Date      Name            Emp_list
----- --------- --------------- ---------------------------------------------
30 07-DEC-02 Raphaely Raphaely; Khoo
30 18-MAY-03 Khoo Raphaely; Khoo
40 07-JUN-02 Mavris Mavris
50 01-MAY-03 Kaufling Kaufling; Ladwig
50 14-JUL-03 Ladwig Kaufling; Ladwig
70 07-JUN-02 Baer Baer
90 13-JAN-01 De Haan De Haan; King
90 17-JUN-03 King De Haan; King
100 16-AUG-02 Faviet Faviet; Greenberg
100 17-AUG-02 Greenberg Faviet; Greenberg
110 07-JUN-02 Gietz Gietz; Higgins
110 07-JUN-02 Higgins Gietz; Higgins

有什么建议吗?

最佳答案

您可以使用avepaste:

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

关于r - 按组连接/粘贴列并添加到原始数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20527722/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com