How to calculate mean for multiple columns in R with colMeans

There are multiple ways to calculate the mean for a column in R. So if you have a small amount of column. Or only need the mean of one of the column, you could use the mean() function. We’ll see later how to do it with colMeans().

myMean <- mean(id_mat[,2])
str(myMean)
> 0.9970131

You can’t do a range on the column. Well, you can, but you won’t get the result you might desired. Because it’ll calculate the mean of all the numbers summing up all columns into one mean integer if you did mean(id_mat[,2:4]).

However, If you want to calculate the mean for each column. And, end up with an array of mean values use the colMeans() function

myMean <- colMeans(id_mat[,1:4])
str(myMean)
> 4.5000000 0.9970131 0.9966084 0.9965288

After that, with colMeans() output you’ll get the array. An array of each mean value for each column in your data frame.

Source: https://www.rdocumentation.org/packages/analytics/versions/3.0/topics/colmean