alki
alki

Reputation: 3584

R Return max count in vector

How would you return the number that repeats the most in a number vector?

For example I would like to return 1 in

x <- c(1,1,2)

Upvotes: 2

Views: 4742

Answers (1)

Matthew Lundberg
Matthew Lundberg

Reputation: 42639

> t <- table(x)
> names(t)[which.max(t)]
[1] "1"

This returns the first value with the most entries. To return them all:

> names(t)[t == max(t)]
[1] "1"

This is the same for your data. Here the two expressions would differ:

> x <- c(1,1,1,2,3,4,4,4,5,6,6,6)
> t <- table(x)
> names(t)[t == max(t)]
[1] "1" "4" "6"

Upvotes: 5

Related Questions