将 R Dataframe 从长格式转换为宽格式并连接字符串值
Convert R Dataframe from long to wide format and concatenate string values
我有这样一个数据框:
df <- data.frame (Subject = c(1,1,1,2,2,3,3), Product = c("A","B","C","B","C","A","D")
我想像这样替换它(变成 "wide" 格式):
df_replace <- data.frame(Subject = c(1,2,3), Product = c("A;B;C","B;C","A;D"))
新产品值应该是给定主题的原始产品值的串联字符串。
我正在试验 dcast ...但我还没有找到继续前进的方法。 (但我假设......这很简单)。
您可以使用 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
我有这样一个数据框:
df <- data.frame (Subject = c(1,1,1,2,2,3,3), Product = c("A","B","C","B","C","A","D")
我想像这样替换它(变成 "wide" 格式):
df_replace <- data.frame(Subject = c(1,2,3), Product = c("A;B;C","B;C","A;D"))
新产品值应该是给定主题的原始产品值的串联字符串。
我正在试验 dcast ...但我还没有找到继续前进的方法。 (但我假设......这很简单)。
您可以使用 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