通过id组合向量来合并行

时间:2018-08-10 00:58:27

标签: r dataframe vector rows

我无法转换此内容

Name(id)    Food 

John        Apple  
John        Beans
Anna        Apple
Anna        Banana

对此:

Name(id)    Food

John        c(Apple,Beans)
Anna        c(Apple,Banana)

我找到了一个解决Python类似问题的方法: Combine rows by id 但无法在R上做类似的事情。

1 个答案:

答案 0 :(得分:1)

# import necessary package   
library(dplyr)

# reproduce the data
df <- data_frame(
  `Name(id)` = c("John", "John", "Anna", "Anna"),
  Food = c("Apple", "Beans", "Apple", "Banana")
)

# group by name and store food in a list
df2 <- df %>%
  group_by(`Name(id)`) %>%
  summarise(Food = list(Food))

df2
# # A tibble: 2 x 2
#   `Name(id)` Food     
#   <chr>      <list>   
# 1 Anna       <chr [2]>
# 2 John       <chr [2]>