0

It looks like this code is trying to find the winners of an election in each year, state, and district, only including those who won by a margin of 5% or less.

Im trying to create a code that finds the winners an election in each year, state and district, only including those who won by a margin of 5% or less. I have created the following code but repeatedly get error, and i cant seem to understand why. Can someone please help me understand what im doing wrong? :)

tab_relevant %>%
  group_by(year, state, district) %>%
  {
    if (tab_relevant$candidatevotes/tab_relevant$totalvotes <= 0.05) {
      slice_max(tab_relevant$candidatevotes)
    } else {
      return(FALSE)
    }
  } -> winner

  • 1
    Welcome to SO, nesehorn! Questions on SO (especially in R) do much better if they are reproducible and self-contained. By that I mean including sample representative data (perhaps via `dput(head(tab_relevant))` or building data programmatically (e.g., `data.frame(...)`), possibly stochastically), perhaps actual output (with verbatim errors/warnings) versus intended output. Refs: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Dec 08 '22 at 17:36
  • The first issue is most likely that your condition `tab_relevant$candidatevotes/tab_relevant$totalvotes <= 0.05` is a vector which on R >= 4.2.0 will result in an error `the condition has length > 1`. Second `slice_max(tab_relevant$candidatevotes)` will not work either as slice_max expects a dataframe as its first argument not a vector. Third, an `if` has nothing to `return`. Finally, not tested but IMHO you could achieve your result without an if by first filtering for margins <= .05 and afterwards using `slice_max` – stefan Dec 08 '22 at 18:43

0 Answers0