R Mean, Median & Mode - R Programming language

How mean, median & mode functions are used in R?

R uses many in-built functions to perform Statistical analysis and most of these functions are part of R base package. These functions take R vector as an input along with the arguments and give the result.

Let’s discuss mean, median and mode functions.

Mean

Mean is calculated by taking sum of the values and dividing with number of values in a data series.

mean()function is used for calculating this in R.

Syntax

Basic syntax for calculating mean in R is

Below is the description of the parameters used

  • x is the input vector.
  • trim is used to drop some observations from both end of the sorted vector.
  • na.rm is used to remove missing values from the input vector.

Example

When above code is executed, it produces following result

Applying Trim Option

When trim parameter is supplied, values in vector will be sorted and then the required numbers of observations will be dropped from calculating the mean.

When trim = 0.3, 3 values from each end will be dropped from the calculations to find mean.

In this case, sorted vector is (−21, −5, 2, 3, 4.2, 7, 8, 12, 18, 54) and the values removed from the vector for calculating mean are (−21,−5,2) from left and (12,18,54) from right.

When above code is executed, it produces following result

Applying NA Option

If there are any missing values, then the mean function returns NA.

For dropping the missing values from the calculation use na.rm = TRUE, which means remove the NA values

When above code is executed, it produces following result

Median

Middle most value in a data series is called median. median() function is used in R to calculate this value.

Syntax

Basic syntax for calculating median in R is

Below is the description of the parameters used

  • x is the input vector.
  • na.rm is used for removing missing values from the input vector.

Example

When above code is executed, it produces following result

Mode

Mode is the value which has highest number of occurrences in a set of data. Unlike mean and median, mode can have both numeric and character data.

R doesn’t have a standard in-built function for calculating mode. Therefore, we are creating a user function to calculate mode of a data set in R. This function takes the vector as input and gives the mode value as output.

Example

When above code is executed, it produces following result

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

R Programming language Topics