Picking the top 5 results for each individual
This is a solution using data.table and without loops.

require(data.table)

pred &lt;- fread("/home/djhurio/Downloads/2023bd19b880.csv")

pred[, id := 1:.N]

# Melt to long format
data_long &lt;- melt(pred, id.vars = "id", measure.vars = names(pred)[2:13],
                  variable.name = "country")

# Order data by id (A) and value (D)
setorderv(data_long, c("id", "value"), order = c(1, -1))

# Numerate records for each id
data_long[, i := 1:.N, by = id]

# Select top 5
data_long &lt;- data_long[i &lt; 6, .(id, country)]

data_long