How to find mode for an R data frame column?

R ProgrammingServer Side ProgrammingProgramming

To find the model for an R data frame column, we can create a function and use it for the calculation. The function for mode is created as written below −

mode<-function(x){which.max(tabulate(x))}

For a data frame called df having numerical column x, this function will be used as mode(df$x).

Consider the below data frame −

Example

 Live Demo

ID<-1:20
x<-rpois(20,2)
df1<-data.frame(ID,x)
df1

Output

  ID x
1  1  1
2  2  2
3  3  3
4  4  1
5  5  1
6  6  0
7  7  2
8  8  0
9  9  1
10 10 2
11 11 5
12 12 1
13 13 2
14 14 2
15 15 2
16 16 3
17 17 2
18 18 1
19 19 6
20 20 1

Finding the mode of x −

mode(df1$x)

[1] 1

Example

 Live Demo

S.no<-1:20
y<-rpois(20,10)
df2<-data.frame(S.no,y)
df2

Output

  S.no y
1  1   12
2  2   13
3  3   11
4  4   7
5  5   6
6  6   5
7  7   8
8  8   13
9  9   6
10 10  8
11 11  12
12 12  7
13 13  15
14 14  6
15 15  13
16 16  14
17 17  10
18 18  11
19 19  7
20 20  14

Finding the mode of y −

mode(df2$y)

[1] 6
raja
Published on 06-Feb-2021 11:48:58
Advertisements