在dplyr中按组返回结果

在dplyr中按组返回结果,r,dplyr,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) } 我们需要summary而不是mutate,而且paste0没有达到预期的输出效果。我们需要折叠 myfunc<-f

我试图返回每组的结果。将每个组传递到新函数的正确方法是什么

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)
}

我们需要
summary
而不是
mutate
,而且
paste0
没有达到预期的输出效果。我们需要
折叠

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
myfunc%
分组依据(ballot1.y)%>%
总结(res=myfunc(ans))
#一个tibble:2x2
#气球
#       
#1         1   3,4
#2         2   5,6
一个方便的功能是
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