R - Finding the Most Frequent Element in a Vector
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
)
(
result
)
String vector
charv
<-
c
(
"google"
,
"runoob"
,
"taobao"
,
"runoob"
,
"runoob"
)
The computed result
result
<-
getmode
(
charv
)
(
result
)
The output of the code above is:
[1] 2
[1] "runoob"
R Language Examples