I haven’t delved too deep into tidyeval and quasiquotation yet, but I have a case where it seems like it makes sense to use and I need some help to make it work.
Say I have a tibble in wide format where each row is an election district and each column is the number of votes a candidate received. I want to calculate to total votes per district and the proportion of votes each candidate received in each district.
library(tidyverse) votes <- tribble( ~district, ~a, ~b, ~c, "dist1", 20L, 5L, 10L, "dist2", 25L, 5L, 15L, "dist3", 10L, 15L, 15L, ) votes #> # A tibble: 3 x 4 #> district a b c #> <chr> <int> <int> <int> #> 1 dist1 20 5 10 #> 2 dist2 25 5 15 #> 3 dist3 10 15 15
If I were just calculating it for this set of candidates, I would do something like the following:
(edited to include
rowise()) for expected totals)
votes %>% rowwise() %>% mutate( total = sum(a + b + c), a_prop = a / total, b_prop = b / total, c_prop = c / total ) #> Source: local data frame [3 x 8] #> Groups: <by row> #> #> # A tibble: 3 x 8 #> district a b c total a_prop b_prop c_prop #> <chr> <int> <int> <int> <int> <dbl> <dbl> <dbl> #> 1 dist1 20 5 10 35 0.571 0.143 0.286 #> 2 dist2 25 5 15 45 0.556 0.111 0.333 #> 3 dist3 10 15 15 40 0.250 0.375 0.375
But where I’m having trouble is if I want to write a function to do this where there could be any number of candidates with any possible name. I think this is a case where I would want to use
:= in my function, but I’m not really sure how to go about it unquoting each element of the dots list to create a new column.