Calculate the Median Absolute Deviation in R Programming – mad() Function
Last Updated :
05 Jul, 2023
The Median Absolute Deviation is calculated in R Language using the mad() function. It is a statistical measurement of a dataset’s dispersion or variability. Due to its resistance to outliers and extreme values, the MAD is a reliable substitute for the standard deviation.
The Median Absolute Deviation (MAD) is calculated using the following formula:
MAD is equal to median(|xi – x)|.
where:
Each observation in the dataset is represented by xi.
The dataset’s median is represented as median(x).
Syntax: mad(x) Parameters: x: Vector
Calculate MAD for vectors :
We can calculate the Median Absolute Deviation for vectors.
Example 1:
Output:
[1] 2.9652
Example 2:
R
x <- c (1, 4, 2, 3, 7, 3, 8, 9, 2)
mad (x)
|
Output:
[1] 1.4826
Calculate MAD for a single column in a data:
We can calculate MAD for a single column in a data set so we can take the iris dataset.
R
data (iris)
mad (iris$Sepal.Width)
|
Output:
[1] 0.44478
Calculate MAD for multiple columns in a data:
With the help of apply function, we can calculate the Median absolute deviation for multiple columns.
R
library (dplyr)
data= select (iris,-( 'Species' ))
sapply (data,mad)
|
Output:
Sepal.Length Sepal.Width Petal.Length Petal.Width
1.03782 0.44478 1.85325 1.03782
We can calculate the mad for multiple columns in a dataset with the help of sapply function. we remove the species column from the data because the mad function only works on numerical columns.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...