R Mean

The mean (or average) in R is calculated using the mean() function. It is a measure of central tendency that represents the sum of all values divided by the number of values.

Key Topics

Mean Example

# Calculating the mean
values <- c(10, 20, 30, 40, 50)
mean_value <- mean(values)

print(mean_value)

Output:

[1] 30

Code Explanation: The mean() function calculates the average of the values in the vector values. The mean is 30.

Handling NA Values in Mean

Use the na.rm = TRUE argument to ignore NA values when calculating the mean.

# Calculating mean with NA values
values_with_na <- c(10, 20, NA, 40, 50)
mean_value <- mean(values_with_na, na.rm = TRUE)

print(mean_value)

Output:

[1] 30

Code Explanation: The na.rm = TRUE argument removes NA values before calculating the mean.

Key Takeaways

  • The mean() function calculates the average value of a numeric vector.
  • Use na.rm = TRUE to ignore NA values.
  • The mean is a common measure of central tendency in data analysis.