gpt4 book ai didi

R数据表从不同行添加列

转载 作者:行者123 更新时间:2023-12-02 08:06:26 25 4
gpt4 key购买 nike

假设我有这个数据表:

Name  |  Pet  | Hobby    | Sibling
------------------------------------------
Bob | Dog | Running | Linda
Ross | Cat | Hiking | Howie
Linda | Mouse | Beaches | Bob
Howie | Plant | Gaming | Ross

接下来,我想将 sibling 的信息添加到同一行。 sibling 的信息在表中。所以基本上你会找到 sibling 的行并将 sibling 的行'Pet'和'Hobby'附加到该行

Name  |  Pet  | Hobby    | Sibling | Sibling's Pet | Sibling Hobby's
-----------------------------------------------------------------
Bob | Dog | Running | Linda | Mouse | Beaches #Cols appended from Row 3 above
Ross | Cat | Hiking | Howie | Plant | Gaming #Cols appended from Row 4 above
Linda | Mouse | Beaches | Bob | Dog | Running #Cols appended from Row 1 above
Howie | Plant | Gaming | Ross | Cat | Hiking #Cols appended from Row 2 above

最佳答案

这是一个使用自连接和按引用更新的 data.table 方法:

dt[dt, on = c("Sibling" = "Name"), `:=`(sib_pet = i.Pet, sib_hob = i.Hobby)]

# Name Pet Hobby Sibling sib_pet sib_hob
#1: Bob Dog Running Linda Mouse Beaches
#2: Ross Cat Hiking Howie Plant Gaming
#3: Linda Mouse Beaches Bob Dog Running
#4: Howie Plant Gaming Ross Cat Hiking

关于R数据表从不同行添加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51045876/

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