Q:

Apply function within dplyr group

I'm trying to calculate the number of seats parties should have in municipal councils using a function from the electoral package, and have a long-format dataframe that is sorted according to municipalities.
However, I seem unable to get the function to work within the groups, and instead get the following error: 

Error in seats_ha(parties = mandates$party, votes = mandates$votes, n_seats = 25,  :    every party name must be unique

I have tried using both do() and group_map(), as this is what was suggested in this thread: Run a custom function on a data frame in R, by group, and summarise would not work since the function is expected to return several rows of values, not one summary value.
I have also tried using the dHondt()-function from the coalitions package, but to no avail, just a different error:
When using do: 

Error: Results 1, 2 must be data frames, not integer

When using group_map: 

Error: Can't convert an integer vector to function

Does anyone have an idea on how to solve this? :) 
Some sample code:
library(tidyverse)
library(electoral)    
mandates <- data.frame(municipality = c("A","A","A","B","B","B"),
                           party = c("1","2","3","1","2","3"),
                           votes = c(125,522,231,115,321,12),
                           seats = c(25,25,25,25,25,25)) 
    mandates <- mandates %>% group_by(municipality) %>% 
            group_map(seats_ha(parties = mandates$party, votes = mandates$votes, n_seats = 25, method = "dhondt"))

Preferably I'd like it to use the seats variable for n_seats, since there are a different number of seats in each municipality, but getting it to work with 25 seats set is a good start. 

A:

you can simply use mutate in this case:
mandates %>% group_by(municipality) %>% 
 mutate(x = seats_ha(parties = party, votes = votes, n_seats = 25, method = "dhondt"))
    # A tibble: 6 x 5
# Groups:   municipality [2]
  municipality party votes seats     x
  <fct>        <fct> <dbl> <dbl> <int>
1 A            1       125    25     3
2 A            2       522    25    15
3 A            3       231    25     7
4 B            1       115    25     6
5 B            2       321    25    19
6 B            3        12    25     0

Mutate can always be used when applying a function which takes (one or more) vector arguments and returns a vector of the same size.
If you want to use n_seats as well you could group with respect to municipality and seats (I would assume that the number of seats within each municipality is the same). Therefore:
mandates %>% group_by(municipality, seats) %>% 
 mutate(x = seats_ha(parties = party, votes = votes, n_seats = seats[1], method = "dhondt"))

