-1

I have a dataset and I would like to concatenate the rows by specific id

 id <- c(1,1,1,2,2,2,2)
 location<- c("Mumbai", "Newyork", "Jaipur", "Paris", "London", "Kentucky", "Dublin") 
df <- data.frame(id, location)

id   location 
1    Mumbai
1    Newyork
1    Jaipur
2    Paris
2    London
2    Kentucky
2    Dublin

 paste(location, collapse="")

I would like to create a column called path for each id which concatenates the rows based on id to get "Mumbai-Newyork-Jaipur" and "Paris-London-Kentucky-Dublin". Any thoughts?

user3570187
  • 1,743
  • 3
  • 17
  • 34

1 Answers1

1
id <- c(1,1,1,2,2,2,2)
location<- c("Mumbai", "Newyork", "Jaipur", "Paris", "London", "Kentucky", "Dublin") 
df <- data.frame(id, location)

library(dplyr)

df %>%
  group_by(id) %>%
  mutate(path = paste(location, collapse = "-"))
ebyerly
  • 662
  • 5
  • 14