Home > Back-end >  How to find students who is the third place? [duplicate]
How to find students who is the third place? [duplicate]

Time:09-22

I have data that shows every students' score and I have to find out who are in the third place. I have to make a list of test scores and a list of students' names.

If there are two or more people who get the same score and occupy third place, the output must show all of the names. I still have no idea how to solve this problem.

example :

names = c('Alex', 'Joy', 'Cindy', 'Lily')
score = c(80, 80,100,90)

Output:

'Students in the third place: Alex, Joy'.

CodePudding user response:

We can use slice_max, by default with_ties = TRUE and then filter the min value

library(dplyr)
df1 %>% 
    slice_max(n = 3, order_by= score) %>% 
    filter(score == min(score))

-output

  names score
1  Alex    80
2   Joy    80

If we need to output in a format

df1 %>% 
    slice_max(n = 3, order_by= score) %>% 
    filter(score == min(score)) %>%
    pull(names) %>%
    {glue::glue("Students in the third place: {toString(.)}")}
Students in the third place: Alex, Joy

data

df1 <- data.frame(names, score)

CodePudding user response:

One solution with rank:

df$names[rank(-df$score) >= 3]
[1] "Alex" "Joy"

If you have ranks greater than 3:

df$names[rank(-df$score) >= 3 & rank(-df$score) <= 4]

Data:

df <- data.frame(
  names = c('Alex', 'Joy', 'Cindy', 'Lily'), 
  score = c(80, 80,100,90)
)
  •  Tags:  
  • r
  • Related