2016-11-06 50 views
0

說我有以下數據幀:「非標」的職能概括功能

df<-data.frame(Name=c(rep("John",3),rep("Paul",2),rep("George",2),"Ringo"), 
    Instrument=c("Guitar","Piano","Drums","Piano","Bass","Guitar","Sitar","Drums")) 
    > df 
     Name Instrument 
    1 John  Guitar 
    2 John  Piano 
    3 John  Drums 
    4 Paul  Piano 
    5 Paul  Bass 
    6 George  Guitar 
    7 George  Sitar 
    8 Ringo  Drums 

我想什麼做的是名族且具有不同的樂器 連接成一個字符串像:

Name  Instruments 
    1 John Guitar,Piano,Drums 
    2 Paul   Piano,Bass 
    3 George  Guitar,Sitar 
    4 Ringo    Drums 

我想通使用GROUP_BY和總結中粘貼應該做的伎倆:

library(dplyr) 
    df <- df %>% 
     group_by(Name) %>% 
     summarise(Instruments = paste(Instrument,sep=",")) 

但相反,我得到了「期望單個值」的錯誤。 group_by只能用於數字函數,如果有的話,是否有人知道是否有解決方法?

回答

2
df <- df %>% 
    group_by(Name) %>% 
    summarise(Instruments = paste(Instrument ,collapse=" ")) 

注意collapse

1

可能也是有用的nest的 '儀器' 爲list

library(dplyr) 
library(tidyr) 
df %>% 
    group_by(Name) %>% 
    nest(Instrument) 

如果我們需要paste在一起,toString是一個方便包裝爲paste(..., collapse=", ")

+1

這實際上比我想要做的更有意義。你超越瞭解決基本的語法問題,並正確處理問題的核心。 – AffableAmbler