The **rowMeans()** function in R can be used to calculate the mean of several rows of a matrix or data frame in R.

This function uses the following basic syntax:

#calculate row means of every column rowMeans(df) #calculate row means and exclude NA values rowMeans(df, na.rm=T) #calculate row means of specific rows rowMeans(df[1:3, ])

The following examples show how to use this syntax in practice.

**Example 1: Calculate Mean of Every Row**

The following code shows how to calculate the mean of every row in a data frame:

#create data frame df <- data.frame(points=c(99, 91, 86, 88, 95), assists=c(33, 28, 31, 39, 34), rebounds=c(30, 28, 24, 24, 28), blocks=c(1, 4, 11, 0, 2)) #view data frame df points assists rebounds blocks 1 99 33 30 1 2 91 28 28 4 3 86 31 24 11 4 88 39 24 0 5 95 34 28 2 #calculate row means rowMeans(df) [1] 40.75 37.75 38.00 37.75 39.75

Here’s how to interpret the output:

- The mean of values in the first row is
**40.75**. - The mean of values in the second row is
**37.75**.

And so on.

**Example 2****: Calculate Mean of Every Row & Exclude NA’s**

The following code shows how to calculate the mean of every row and exclude NA values:

#create data frame with some NA values df <- data.frame(points=c(99, 91, 86, 88, 95), assists=c(33, NA, 31, 39, 34), rebounds=c(30, 28, NA, NA, 28), blocks=c(1, 4, 11, 0, 2)) #view data frame df points assists rebounds blocks 1 99 33 30 1 2 91 NA 28 4 3 86 31 NA 11 4 88 39 NA 0 5 95 34 28 2 #calculate row means rowMeans(df, na.rm=T) [1] 40.75000 41.00000 42.66667 42.33333 39.75000

**Example 3: Calculate Mean of Specific Rows**

The following code shows how to calculate the mean values of specific rows in the data frame:

#create data frame df <- data.frame(points=c(99, 91, 86, 88, 95), assists=c(33, 28, 31, 39, 34), rebounds=c(30, 28, 24, 24, 28), blocks=c(1, 4, 11, 0, 2)) #calculate row means for first three rows only rowMeans(df[1:3, ]) 1 2 3 40.75 37.75 38.00

We can also use the **c()** syntax to select specific rows:

#calculate row means for rows 1, 4, and 5 rowMeans(df[c(1, 4, 5), ]) 1 4 5 40.75 37.75 39.75

**Additional Resources**

The following tutorials explain how to perform other common functions in R:

How to Calculate Standard Deviation of Columns in R

How to Calculate the Mean by Group in R

How to Calculate the Sum by Group in R