79783449

Date: 2025-10-06 07:59:37
Score: 0.5
Natty:
Report link

A few years late, but in case anyone find this thread on google, this works and will give the second highest value, while ignoring all values tied for first:

library(dplyr)

x <- data.frame(name = c("foo","foo","foo","foo","bar","bar","bar","bar"), 
           value = c(100,200,300,300,200,100,200,600))

x %>% 
  group_by(name) %>%
  summarise(maxValue = max(value),
            secondValue = max(value[value != maxValue]),
            thirdValue = max(value[value != maxValue & value != secondValue]))

Output:

  name  maxValue secondValue thirdValue
  <chr>    <dbl>       <dbl>      <dbl>
1 bar        600         200        100
2 foo        300         200        100

You could keep extending that strategy for a fourth and fifth value, but at that point you'd be better off writing a function for it.

Or if you only want the second value:

x %>% 
  group_by(name) %>%
  summarise(secondValue = max(value[value != max(value)]))
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Unregistered user (0.5):
  • Low reputation (1):
Posted by: RudyR