Here you can use the idiom which(x == max(x)) and use apply() to run it on each line:
apply(mydata[, -1], 1, function(x) which(x == max(x)))
which gives:
> apply(mydata[, -1], 1, function(x) which(x == max(x))) [[1]] v4 4 [[2]] v1 v2 1 2 [[3]] v1 1 [[4]] v2 2 [[5]] v2 2 [[6]] v2 v4 2 4
The list contains the index vectors of the variable (s) that are maximum, and the names of these vectors can be extracted using names() to indicate the actual variable ID:
> out <- apply(mydata[, -1], 1, function(x) which(x == max(x))) > names(out[[2]]) [1] "v1" "v2" > lapply(out, names) [[1]] [1] "v4" [[2]] [1] "v1" "v2" [[3]] [1] "v1" [[4]] [1] "v2" [[5]] [1] "v2" [[6]] [1] "v2" "v4"
If your data may contain NA , then we need to be a little smarter, for example.
apply(mydata[, -1], 1, function(x, na.rm = FALSE) which(x == max(x, na.rm = na.rm)), na.rm = TRUE)
in which we can proceed to ignore NA or not.
source share