0
0
R-programmingHow-ToBeginner · 3 min read

How to Calculate Mean in R: Simple Guide with Examples

In R, you calculate the mean of a set of numbers using the mean() function. Simply pass a numeric vector to mean(), and it returns the average value.
📐

Syntax

The basic syntax to calculate the mean in R is:

  • mean(x, na.rm = FALSE)

Here, x is a numeric vector of values. The na.rm argument tells R whether to ignore NA (missing) values; FALSE means do not ignore them, TRUE means ignore them.

r
mean(x, na.rm = FALSE)
💻

Example

This example shows how to calculate the mean of a numeric vector and how to handle missing values.

r
numbers <- c(10, 20, 30, 40, 50)
mean_value <- mean(numbers)

numbers_with_na <- c(10, 20, NA, 40, 50)
mean_ignore_na <- mean(numbers_with_na, na.rm = TRUE)

mean_value
mean_ignore_na
Output
[1] 30 [1] 30
⚠️

Common Pitfalls

One common mistake is not handling NA values, which causes mean() to return NA. Always use na.rm = TRUE if your data might have missing values.

Another mistake is passing non-numeric data, which will cause an error.

r
values_with_na <- c(5, 10, NA, 15)

# Wrong: missing values cause NA result
mean(values_with_na)

# Right: ignore missing values
mean(values_with_na, na.rm = TRUE)
Output
[1] NA [1] 10
📊

Quick Reference

FunctionDescription
mean(x)Calculate mean of numeric vector x
mean(x, na.rm = TRUE)Calculate mean ignoring NA values
mean(c())Returns NaN for empty vector
mean(x, trim = 0.1)Calculate mean after trimming 10% of values from each end

Key Takeaways

Use the mean() function to calculate the average of numeric data in R.
Set na.rm = TRUE to ignore missing values and avoid NA results.
Pass only numeric vectors to mean() to prevent errors.
mean() can trim values with the trim argument for robust averages.
Empty vectors passed to mean() return NA.