0% found this document useful (0 votes)
7 views9 pages

Calculate Mode in R: User-Defined Functions

Uploaded by

Sri Krishna
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views9 pages

Calculate Mode in R: User-Defined Functions

Uploaded by

Sri Krishna
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Mode

 The mode is a statistical measure used to identify the value that occurs most frequently in
a dataset.
 Mode can have both numeric and character data.
 R does not have a built-in function to directly calculate the mode.
Example:
1) data<- c(10, 5, 8, 7.5, 8, 45, 40, 51, 5, 16.5, 27, 7.8, 8, 10, 15)
mode(data)
[1] “numeric”
2) X<-c(“A”,”B”,”C”,”A”)
mode(X)
[1] “character”
1
1)User-defined Function:
 we create a user function to calculate mode of a data set in R.
 This function takes the input and gives the mode value as output.

Syntax:
calculate _mode<- function(data) {
# Function implementation to find the mode
}

2
Example:
find_mode <- function(data) {
# Count occurrences of each unique value
counts <- table(data)
# Find the maximum count
max_count <- max(counts)
# Extract the value(s) with the maximum count (mode)
modes <- names(counts)[which(counts == max_count)]
return(modes)}

3
Using mode() Function in R DataFrame
# Create Data Frame
> df=[Link](id=c(11,22,33,11,55),name=c(“spark”,”R”,”node js”,”R”),
price=c(144,NA,144,567,567))
> df
# Usage of mode() Function
> find_mode(df$id)
> find_mode(df$name)
> find_mode(df$price)

4
Using mode() with R Vector
# mode() from Vector
 v1 <- c(1,22,3,5,3,1)
 find_mode(v1)
 v2 <- c("AA","BB","CC","AA","CC","CC")
 find_mode(v2)
 v3 <- c(144,NA,144,567,567)
 find_mode(v3)

5
Using mode() with R Factor
 factor_vector <- factor(c("a", "b", "b", "c", "c", "c", "d"))
 find_mode(factor_vector)
 Z<-factor(c(65,78,81,78,81,90)
 find_mode(Z)

6
2) Using DescTools package
> [Link]("DescTools")
 library("DescTools“)
Example:
 marks<-c(87,78,57,78,87,78,87,64)
 Mode(marks)
[1] 78 87
attr(,”freq”)
[1] 3

7
3) Using modeest package
> [Link]("modeest")
 library(modeest)
Example:
 factor_vector <- factor(c("a", "b", "b", "c", "c", "c", "d"))
 mode_factor <- mfv(factor_vector)
 print(mode_factor)

8
Finding mode in CSV file

 Import the library

 Import the data using [Link]()

 Compute the mode value

Example:

d<-[Link](“[Link]”)

mode<-mfv(d$Age)

print(mode)
9

You might also like