1

I've run this code

var <- c("A","A","A","A","B","B","B","B","B","B","C","C","C")
table(var)
> table(var)
var
A B C 
4 6 3 

The maximum frequency is 6, for factor "B". Is there a function that just returns the name of the factor which has the highest frequency, "B". Any help greatly appreciated. Thanks

H.Cheung
  • 855
  • 5
  • 12

2 Answers2

1

A possible solution:

library(tidyverse)

var <- c("A","A","A","A","B","B","B","B","B","B","C","C","C")
table(var) %>% which.max %>% names

#> [1] "B"

In base R:

names(which.max(table(var)))
PaulS
  • 21,159
  • 2
  • 9
  • 26
1

Using tidyverse:

library(tidyverse)

var <- c("A","A","A","A","B","B","B","B","B","B","C","C","C")

df <- tibble(var = var)

df %>% 
  count(var,sort = TRUE) %>% 
  slice(1) %>% 
  pull(var)
#> [1] "B"

Created on 2021-11-17 by the reprex package (v2.0.1)

jpdugo17
  • 6,816
  • 2
  • 11
  • 23