在dplyr中按组返回结果

时间:2017-10-24 16:46:41

标签: r 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)
}

目标

GROUP RES
1     3,4
2     5,6

1 个答案:

答案 0 :(得分:3)

我们需要summarise而不是mutatepaste0也没有做预期的输出。我们需要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

方便的功能是toString paste(., collapse=", ")