From the following table, I have a frequency table, and while I am able to find the maximum, I would prefer to have the "name" of the variable instead, so 6 would be the answer, instead of 8.
x <- c(1,3,6,7,2,6,7,8,8,5,1,2,3,9,5,4,1,8,3,4,3,6,8,5,8,7,4,6,6,6,6,6)
t <- table(x)
## x
## 1 2 3 4 5 6 7 8 9
## 3 2 4 3 3 8 3 5 1
max(t)
## [1] 8
I know there is a which.max()
function; however, the code I am trying to implement involves an 'n' number of variables, so I will be unable to write out each variable name each time the code is run.
We can use which.max
to return the index of the first max value and use that to get the names
names(which.max(t))
If there are ties for max
value, create a logical vector
with ==
, get all the position index with which
and extract the names
names(which(t == max(t)))