Combine rows by id making vectors
Asked Answered
E

1

0

I'm having trouble to convert this:

Name(id)    Food 

John        Apple  
John        Beans
Anna        Apple
Anna        Banana

To this:

Name(id)    Food

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

I've found a solution to a similar problem with Python: Combine rows by id but couldn't do something similar on R.

Engedus answered 10/8, 2018 at 0:58 Comment(1)
Most probably you need this #15934458Queenqueena
R
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]>
Rauwolfia answered 10/8, 2018 at 1:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.