Search code examples
rnames

Select the name of a certain value in a table (e.g. max)


I have a vector of numbers. Let's call it mydata:

str(mydata)
# num [1:236] 2 1 1 2 2 1 2 1 2 2 ...

I can then count each value using table:

table(mydata)
# mydata
#  1    2    9  10 
# 20  200   14   2

Now, I want to select the value with the highest count (in this case, "2").

I can find the highest count (e.g. 200 in this case) by using the max function: max(table(mydata)). But how to get the name associated with the max count in the table, i.e. "2"?


Solution

  • A table is very much like a list or a data frame, in that it has values and names (attributes) that are accessible through vector subsetting.

    > mydata <- c(rep(1, 20), rep(2, 200), rep(9, 14), rep(10, 2))
    > tab <- table(mydata)
    > tab
    ## mydata
    ##   1   2   9  10 
    ##  20 200  14   2
    > names(tab)
    ## [1] "1"  "2"  "9"  "10" 
    > c(val = names(tab)[tab == max(tab)], freq = max(tab))
    ##  val  freq 
    ##  "2" "200"
    

    The following are equivalent

    > tab[ names(tab)[tab == max(tab)] ]
    ##   2 
    ## 200
    > tab["2"]
    ##   2
    ## 200
    

    Other useful things to know about an object is described in its attributes

    > attributes(tab)
    $dim
    [1] 4
    
    $dimnames
    $dimnames$mydata
    [1] "1"  "2"  "9"  "10"
    
    $class
    [1] "table"