提问者:小点点

如何连接R数据帧中按列分组的行?[重复]


下面给出了示例数据框。它包含列名和我要创建的新列。

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列连接城市行,并在我的数据框中创建expected_city_col。


共1个答案

匿名用户

一种选择是在按'ID'分组后,将'city'元素粘贴到mutate中以创建一个新列

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