gpt4 book ai didi

r - 将新列添加到数据框中,并将重复值粘贴在一起

转载 作者:行者123 更新时间:2023-12-01 07:01:49 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Collapse / concatenate / aggregate a column to a single comma separated string within each group

(5 个回答)


2年前关闭。




我有一个 df看起来像这样:

ID  Country
55 Poland
55 Romania
55 France
98 Spain
98 Portugal
98 UK
65 Germany
67 Luxembourg
84 Greece
22 Estonia
22 Lithuania

凡有些 ID重复,因为它们属于同一组。我想做的是 paste一起 CountryID , 有这样的输出。

enter image description here

到目前为止,我试过 ifelse(df[duplicated(df$ID) | duplicated(df$ID, fromLast = TRUE),], paste('Countries', df$Country), NA)但这不是检索预期的输出。

最佳答案

使用 data.table

library(data.table)

setDT(df)[, New_Name := c(paste0(Country, collapse = " + ")[1L], rep(NA, .N -1)), by = ID]

#df
#ID Country New_Name
#1: 55 Poland Poland + Romania + France
#2: 55 Romania <NA>
#3: 55 France <NA>
#4: 98 Spain Spain + Portugal + UK
#5: 98 Portugal <NA>
#6: 98 UK <NA>
#7: 65 Germany Germany
#8: 67 Luxembourg Luxembourg
#9: 84 Greece Greece
#10: 22 Estonia Estonia + Lithuania
#11: 22 Lithuania <NA>

关于r - 将新列添加到数据框中,并将重复值粘贴在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56949656/

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