如何串联R Data框架中按列分组的行?

时间:2019-02-28 17:22:57

标签: r concatenation

样本数据帧如下。它包含列名和我要创建的新列。

df1<-data.frame(city=c("Delhi","Pune","Mumbai","Bangalore","Indiranagar"),ID=c(1,1,1,2,2),expected_city_col=c("Delhi Pune Mumbai","Delhi Pune Mumbai","Delhi Pune Mumbai","Bangalore Indiranagar","Bangalore Indiranagar"))

我想按ID列连接City行,并在数据框中创建Expected_city_col。

1 个答案:

答案 0 :(得分:1)

一个选项是在将paste中的“城市”元素按“ ID”分组后,mutate一起创建新列

library(dplyr)
df1 %>% 
   group_by(ID) %>% 
   mutate(newcol = paste(city, collapse= ' '))