I have a similar problem as described here (R - find first, second and third largest values by row). I would like to output the five highest values by row as described in the other thread. In addition I need five other columns with the name of the column header of that value. I did this for the v1 column as an example below (names_first). I have been trying for hours but no success.
df <- data.frame(v1 = c(0,1,2,3,4,NA),
v2 = c(23,6,3,21,4,NA),
v3 = c(22,22,24,87,6,NA),
v4 = c(2,32,6,58,5,NA),
v5 = c(5,22,65,86,4,NA)
)
df$first <- apply(df, 1, max)
df$second <- apply(df, 1, function(x) -sort(-x[1:5])[2])
df$third <- apply(df, 1, function(x) -sort(-x[1:5])[3])
df$fifth <- apply(df, 1, function(x) -sort(-x[1:5])[4])
df$sixth <- apply(df, 1, function(x) -sort(-x[1:5])[5])
df$sixth <- apply(df, 1, function(x) -sort(-x[1:5])[5])
names_first=c("v2","v4","v5","v3","v3")
df <- cbind(df,names_first)