2

Sample data frame is given below . It contains column names and new column that I want to create .

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"))

I want to concatenate City rows by ID column , and create expected_city_col in my data frame .

Yogesh Kumar
  • 609
  • 6
  • 22
  • Try `library(dplyr);df1 %>% group_by(ID) %>% mutate(newcol = paste(city, collapse= ' '))` – akrun Feb 28 '19 at 17:24

1 Answers1

1

One option is after grouping by 'ID', paste the 'city' elements together in mutate for creating a new column

library(dplyr)
df1 %>% 
   group_by(ID) %>% 
   mutate(newcol = paste(city, collapse= ' '))
akrun
  • 874,273
  • 37
  • 540
  • 662