How to Calculate the Average of a data frame in R

To calculate the average of a data frame column in R, use the mean() function. The mean() function takes the column name as an argument and calculates the mean value of that column.

To create a data frame, use the data.frame() function.

df <- data.frame(a1 = 1:3, a2 = 4:6, a3 = 7:9)
cat("The average of the a2 column is", "\n")


   a1  a2  a3
1  1   4   7
2  2   5   8
3  3   6   9

The average of the a2 column is
[1] 5

In this example, the mean() function takes the second column, a2, as an argument because we need to find the average of the a2 column, which is 5.

After all, the values of the a2 column are (4, 5, 6), the sum is 15, and the total number is 3. So the average is 15 / 3 = 5.

That’s it.

Leave a Comment