下面给出了示例数据框。它包含列名和我要创建的新列。
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。
一种选择是在按'ID'分组后,将'city'元素粘贴到
mutate
中以创建一个新列
library(dplyr)
df1 %>%
group_by(ID) %>%
mutate(newcol = paste(city, collapse= ' '))