Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R - Finding the Most Frequent Element in a Vector

R - Finding the Most Frequent Element in a Vector

R Language Examples R Language Examples

In the following example, we define a function to find the element that appears most frequently in a vector.

Example

Create a vector

getmode

<-

function

(

v

)

{

   uniqv

<-

unique

(

v

)

   uniqv

[

which.max

(

tabulate

(

match

(

v, uniqv

)

)

)

]

}

Numeric vector

v

<-

c

(

2

,

1

,

2

,

3

,

1

,

2

,

3

,

4

,

1

,

5

,

5

,

3

,

2

,

3

)

The computed result

result

<-

getmode

(

v

)

print

(

result

)

String vector

charv

<-

c

(

"google"

,

"runoob"

,

"taobao"

,

"runoob"

,

"runoob"

)

The computed result

result

<-

getmode

(

charv

)

print

(

result

)

The output of the code above is:



[1] 2

[1] "runoob"

R Language Examples R Language Examples