# R Mean, Median, and Mode

Mean, Mode, and Median are measurements of central tendency. In other words, it tells you where the "middle" of a data set is.

Each of these statistics defines the middle differently.

• The mean is the average of a data set.
• The mode is the most common number in a data set.
• The median is the middle of the set of numbers.

## Calculate Mean in R

In R, we use the `mean()` function to calculate the mean. For example,

``````# vector of marks
marks <- c(97, 78, 57, 64, 87)

# calculate average marks
result <- mean(marks)

print(result)``````

Output

`[1] 76.6`

In the above example, we have used the `mean()` function to calculate the average result of the marks vector.

## Calculate Median in R

We use the `median()` function to calculate the median in R. For example,

``````# vector of marks
marks <- c(97, 78, 57, 64, 87)

# find middle number of marks
result <- median(marks)

print(result)``````

Output

`[1] 78`

In the above example, we have used the `median()` function to find the middle value of the marks vector.

## Calculate Mode in R

In R, unlike mean and median, there's no built-in function to calculate mode. We need to create a user defined function to calculate mode. For example,

``````# vector of marks
marks <- c(97, 78, 57,78, 97, 66, 87, 64, 87, 78)

# define mode() function
mode = function() {

# calculate mode of marks
return(names(sort(-table(marks)))[1])
}

# call mode() function
mode()``````

Output

`[1] "78"`

In the above example, we have created a function named `mode()` to calculate the mode of the marks vector.

Inside the function, we have used the `table()` function to create a categorical representation of data with the variable names and the frequency in the form of a table.

We will sort marks in descending order and will return the 1st value from the sorted values.

Finally, we have called the `mode()` function and it returned the most common number in marks i.e. 78

Note: We have used vectors to demonstrate how to calculate mean, median, and mode. We can also calculate mean, median, and mode from CSV file, larger datasets, etc in a similar way.