我想知道如何合并数据框中的重复行,然后将重复的值合并到另一列中.
以下是现有数据框和两个可作为解决方案可接受的数据框的示例
df1 <- data.frame(col1 = c("test1", "test2", "test2", "test3"), col2 = c(1, 2, 3, 4))
df.ideal <- data.frame(col1 = c("test1", "test2", "test3"), col2 = c(1, "2, 3", 4))
df.ideal2 <- data.frame(col1 = c("test1", "test2", "test3"),
col2 = c(1, 2, 4),
col3 = c(NA, 3, NA))
Run Code Online (Sandbox Code Playgroud)
在第一个理想的数据框中,复制的行将折叠,并且该列将添加两个数字.我已经查看了有关堆栈溢出的其他类似问题,但它们都处理了组合行.我需要删除重复的行,因为我有另一个数据集我正在合并它需要一定数量的行.所以,我想保留所有的价值观.谢谢你的帮助!
从去df1到df.ideal,你可以使用集合().
aggregate(col2~col1, df1, paste, collapse=",")
# col1 col2
# 1 test1 1
# 2 test2 2,3
# 3 test3 4
Run Code Online (Sandbox Code Playgroud)
如果你想要df.ideal2,那就更多的是从长到宽的过程中重塑.你可以做
reshape(transform(df1, time=ave(col2, col1, FUN=seq_along)), idvar="col1", direction="wide")
# col1 col2.1 col2.2
# 1 test1 1 NA
# 2 test2 2 3
# 4 test3 4 NA
Run Code Online (Sandbox Code Playgroud)
仅使用基本reshape()功能.