我有一个这样的数据框:
df <- data.frame (Subject = c(1,1,1,2,2,3,3), Product = c("A","B","C","B","C","A","D")
我希望将其替换为(&#34;宽&#34;格式),如下所示:
df_replace <- data.frame(Subject = c(1,2,3), Product = c("A;B;C","B;C","A;D"))
新的Product值应该是给定Subject的原始Product值的连接字符串。
我正在试验dcast ......但我还没有找到前进的方法。 (但我假设......很简单)。
答案 0 :(得分:1)
您可以使用aggregate
。
xy <- read.table(text = "Subject Product
1 ProdA
1 ProdB
1 ProdC
2 ProdB
2 ProdC
2 ProdD
3 ProdA
3 ProdB", header = TRUE)
aggregate(Product ~ Subject, FUN = paste, collapse = ";", data = xy)
Subject Product
1 1 ProdA;ProdB;ProdC
2 2 ProdB;ProdC;ProdD
3 3 ProdA;ProdB