Hi @jynusmac ,
I'm using the tidyverse for your problem
Here's your dataframe again:
max_vot <- data.frame(
P1 = c(310L, 349L, 2831L, 99L, 161L, 1353L, 196L, 113L, 23L),
P2 = c(193L, 111L, 3126L, 56L, 155L, 1261L, 92L, 125L, 47L),
P3 = c(122L, 147L, 3566L, 54L, 70L, 1007L, 123L, 88L, 22L),
P4 = c(30L, 42L, 645L, 18L, 10L, 247L, 43L, 15L, 6L),
P5 = c(47L, 45L, 574L, 41L, 17L, 378L, 39L, 20L, 5L)
)
Create a table that shows 2nd and 3rd highest values, I don't know the background of your data but used the assumption that Pi are "judges" that give "values" for specific votes (vote_id). If the background of your data is different and I misunderstood it, feel free to rename the objects to make the code more explicit:
max_vot_table <- max_vot %>%
#assigne vote_ID (row number) to each row, useful for when we'll pivot to a longer format below
mutate(vote_ID = 1:nrow(.)) %>%
#pivot to long format, we obtain 3 columns: row ID (or vote ID), judge ID (P1, ... P5), value of the vote
pivot_longer(-vote_ID, names_to = "judge", values_to = "value") %>%
#sort by vote_ID (the rows of your source dataframe) and value of the vote in descending order
arrange(vote_ID, desc(value)) %>%
#group by vote_ID to perform our summary on each of these groups
group_by(vote_ID) %>%
#select 2nd or 3rd position from each group
summarise(
second_pos = judge[2],
third_pos = judge[3]
)
The results are in each column of max_vot_table . If you need to export them separately as a vector:
max_vot_table %>% pull(second_pos)
max_vot_table %>% pull(third_pos)
Let me know if you'd rather have a function for this.
There are probably more code-savvy ways to solve this, so maybe worth waiting to see if someone suggests something a bit crispier 