A simple microtask : you are given a data frame of numerical data. You want to find maximum values of each row with corresponding column names, and add them at the right end of the original data frame. Here is my solution using user-defined functions that invokes sort(). May not be an efficient or R-native code though. Leave a comment please for a better solution.
maxval1 = function(x) {
q <- sort(x)
return(q[length(x)])
}
maxcol1 = function(x) {
q <- sort(x)
return(names(q)[length(x)])
}
df <- cbind(df, val1 = apply(df, 1, maxval1), col1 = apply(df, 1, maxcol1))
df <- data.frame(df)
The above code appends maximum value of each row and matching column names at the end of existing data frame df. You only need to replace length(x) by length(x) - k for (k+1)th highest value / index. Or you can replace it with 0, 1, ..., k for lowest value / index.