*75*

The **median absolute deviation** measures the spread of observations in a dataset.

Itâ€™s a particularly useful metric because itâ€™s less affected by outliers than other measures of dispersion like standard deviation and variance.

The formula to calculate median absolute deviation, often abbreviated MAD, is as follows:

**MAD = median(|x _{i} â€“ x_{m}|)**

where:

**x**The i_{i}:^{th}value in the dataset**x**The median value in the dataset_{m}:

The following examples shows how to calculate the median absolute deviation in R by using the built-inÂ **mad()** function.

**Example 1: Calculate MAD for a Vector**

The following code shows how to calculate the median absolute deviation for a single vector in R:

#define data data #calculate MAD mad(data) [1] 11.1195

The median absolute deviation for the dataset turns out to beÂ **11.1195**.

**Example 2: Calculate MAD for a Column in a Data Frame**

The following code shows how to calculate MAD for a single column in a data frame:

#define data data #calculate MAD for columnyin data frame mad(data$y) [1] 2.9652

The median absolute deviation for column *y* turns out to be **2.9652**.

**Example 3: Calculate MAD for Multiple Columns in a Data Frame**

The following code shows how to calculate MAD for multiple columns in a data frame by using theÂ **sapply()** function:

#define data data #calculate MAD for all columns in data frame sapply(data, mad) x y z 2.9652 2.9652 1.4826

The median absolute deviation isÂ **2.9652** for column x,Â **2.9652** for column y, andÂ **1.4826** for column z.

**Related:**Â A Guide to apply(), lapply(), sapply(), and tapply() in R

**Additional Resources**

How to Calculate MAPE in R

How to Calculate MSE in R

How to Calculate RMSE in R