样本数据帧如下。它包含列名和我要创建的新列。
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。
答案 0 :(得分:1)
一个选项是在将paste
中的“城市”元素按“ ID”分组后,mutate
一起创建新列
library(dplyr)
df1 %>%
group_by(ID) %>%
mutate(newcol = paste(city, collapse= ' '))