Hy, I have this dataset and I want reshape the data.
> dvd
ID Item
1 1 Sixth Sense
2 1 LOTR1
3 1 Harry Potter1
4 1 Green Mile
5 1 LOTR2
6 2 Gladiator
7 2 Patriot
8 2 Braveheart
9 3 LOTR1
10 3 LOTR2
11 4 Gladiator
12 4 Patriot
13 4 Sixth Sense
I want put the data in this format.
# ID V1
# 1: 1 Sixth Sense,LOTR1,Harry Potter1,Green Mile,LOTR2
# 2: 2 Gladiator,Patriot,Braveheart
# 3: 3 LOTR1,LOTR2
# 4: 4 Gladiator,Patriot,Sixth Sense
I know that I can do this with data.table using this code
library(data.table)
as.data.table(DF)[, list(list(Item)), by = ID]
But I really want use dplyr package.. It's possible? I'm thinking all day about this and I cannot forget this problem and it's killing me :)
Many thanks for your help
With the dev version of tidyr
( install ), it is simply
nest(DF, Item)
which would be
library(dplyr)
DF %>% group_by(ID) %>%
summarise(Item = list(Item))
I would approach is like so:
DF %>%
group_by(ID) %>%
summarise(V1 = paste0(Item, collapse = ", "))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.