Apply FUN row-wise on data frame with integer and character variables
问题 A completely basic question - and forgive me if it is a duplicate. set.seed(1) df <- data.frame(id=c('a', 'a', 'b', 'b', 'a'), a=sample(1:10, size=5, replace=T), b=sample(1:10, size=5, replace=T), c=sample(1:10, size=5, replace=T)) Then, > df id a b c 1 a 3 9 3 2 a 4 10 2 3 b 6 7 7 4 b 10 7 4 5 a 3 1 8 To return the column name (a, b or c) with the largest value, and if this is in the id variable take the second highest, I use the below function. FUN <- function(r) { top <- names(r[,c('a', 'b