2015-09-01 33 views
1

Hy, 我有這個數據集,我想重新塑造數據。用dplyr軟件包重塑數據

> 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 

我想把這種格式的數據。

#  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 

我知道,我可以data.table使用此代碼

library(data.table) 
as.data.table(DF)[, list(list(Item)), by = ID] 

但我真的想用dplyr包.. 這是可能做到這一點? 我想了一整天關於這一點,我不能忘了這個問題,它的殺了我:)

您的幫助非常感謝

回答

1

我的做法是,像這樣:

DF %>% 
    group_by(ID) %>% 
    summarise(V1 = paste0(Item, collapse = ", ")) 
+0

本傑明,謝謝你的幫助。問候 – Kardu

2

隨着的tidyrinstall)dev的版本,它僅僅是

nest(DF, Item) 

這將是

library(dplyr) 
DF %>% group_by(ID) %>% 
    summarise(Item = list(Item)) 
+0

非常感謝nongkron。問候 – Kardu