Rilcon42
Rilcon42

Reputation: 9765

Return results by group in dplyr

I am trying to return the results of each group. What is the correct way to pass each group into a new function?

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

Upvotes: 1

Views: 62

Answers (1)

akrun
akrun

Reputation: 887028

We need summarise instead of mutate and also paste0 is not doing the intended output. We need to 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

A convenient function is toString which is paste(., collapse=", ")

Upvotes: 3

Related Questions