How to Apply the ave() Function in R Programming (2 Examples)

In this article, I’ll illustrate how to compute averages using the ave function in the R programming language.

Creation of Example Data

x <- 1:5                       # Create example vectors
gr <- c("gr1", "gr1", "gr2", "gr2", "gr3")

Example 1: Calculate Mean of Vector Using ave() Function

ave(x)                         # Apply ave function to vector
# [1] 3 3 3 3 3

Example 2: Calculate Mean by Group Using ave() Function

ave(x, gr)                     # Average by group
# [1] 1.5 1.5 3.5 3.5 5.0

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed