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

C.Cheung
  • 695
  • 3
  • 11

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
  • 10,636
  • 1
  • 7
  • 20
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
  • 5,531
  • 2
  • 9
  • 22