I've tried dplyr's lag function ( v %>% mutate(toTie = lag(count) - count)). This works, but not when there are ties, as any tied observation after the first is compared to an observation with the same value. For example, after the mutate I have this:
rank name count toTie
<dbl> <chr> <dbl> <dbl>
1 1 Mary 100 NA
2 2 Fred 96 4
3 3 Sue 90 6
4 3 Michelle 90 0
5 4 Tom 72 18
This output correctly says Sue, who is ranked third, needs 6 to tie Fred, who is second. But because it compares Michelle to Sue (and not Fred), it says Michelle needs none to tie Sue. This is true, but not the intent. Michelle, like Sue, needs 6 to tie second-place Fred.
Any thoughts on a better approach would be most appreciated.