根据id名称连接行

时间:2016-11-21 21:19:00

标签: r dplyr paste tidyr

我有一个数据集,我希望按特定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="")

我想为每个id创建一个名为path的列,它根据id连接行以获得“Mumbai-Newyork-Jaipur”和“Paris-London-Kentucky-Dublin”。有什么想法吗?

1 个答案:

答案 0 :(得分: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 = "-"))