How to Calculate Mean / Average in R

To calculate a mean or average in R, you can use the mean() function. For example, mean(c(1, 2, 3, 4)) function returns 2.5.

Syntax

mean(x, trim, na.rm)

Example 1: Calculating the mean of a vector

Calculating the mean of a vector

vec <- c(11, 21, 19, 18, 51, 51, 71)

# Calculating average using mean() 
mean(vec)

Output

[1] 34.57143

Example 2: Calculating the mean of a data frame column

Calculating the mean of a data frame column

df <- data.frame(
  id = c(11, 22, 33, 44, 55),
  price = c(19, 46, 21, 11, 18)
)

# Calculate mean of DataFrame column
mean_of_col <- mean(df$price)
mean_of_col

Output

[1] 23

Example 3: Plotting of mean

# Generating 10 random numbers from a standard normal distribution
data <- rnorm(10)

# Calculate the mean
data_mean <- mean(data)

# Plotting the data using base R graphics
plot(1:10, data, pch=19, col="blue", ylim=c(min(data) - 1, max(data) + 1), 
     xlab="Index", ylab="Value", main="Scatter Plot with Mean Overlay")
abline(h=data_mean, col="red", lwd=2) # Overlaying the mean
grid(col="gray")
legend("topright", legend=paste("Mean =", round(data_mean, 2)), col="red", lwd=2)

Output

Plotting the mean values using ggplot2

Related posts

Standard deviation

R Variance

Standard Error in R

Leave a Comment