2017-10-24 4 views
1

各グループの結果を返そうとしています。各グループを新しい関数に渡す正しい方法は何ですか?dplyrでグループ別結果を返します

res<-data.frame(ballot1.y=c(1,2,1,2),ans=c(3,5,4,6))%>%group_by(ballot1.y)%>%mutate(res=head(myfunc(.))) 

myfunc<-function(vals){ 
    paste0(vals) 
} 

GOALは

GROUP RES 
1  3,4 
2  5,6 

答えて

3

我々はsummarise代わりのmutate必要ともpaste0は、意図した出力を行っていません。私たちは、便利な機能がpaste(., collapse=", ")

ある toStringある collapse

myfunc<-function(vals){ 
    paste(vals, collapse=",") 
} 

data.frame(ballot1.y=c(1,2,1,2),ans=c(3,5,4,6))%>% 
    group_by(ballot1.y) %>% 
    summarise(res =myfunc(ans)) 
# A tibble: 2 x 2 
# ballot1.y res 
#  <dbl> <chr> 
#1   1 3,4 
#2   2 5,6 

に必要

関連する問題