# How to find the row mean for columns in an R data frame by ignoring missing values?

To find the row mean for columns by ignoring missing values, we would need to use rowMeans function with na.rm. For example, if we have a data frame called df that contains five columns and some of the values are missing then the row means will be calculated by using the command: rowMeans(df,na.rm=TRUE).

Consider the below data frame −

## Example

Live Demo

x1<-sample(c(NA,rpois(4,5)),20,replace=TRUE)
x2<-sample(c(NA,rpois(4,5)),20,replace=TRUE)
df1<-data.frame(x1,x2)
df1

## Output

   x1  x2
1  NA   2
2  7    9
3  5    8
4  7   NA
5  NA   8
6  7    8
7  5    2
8  5   NA
9  5    6
10 NA   8
11 7    8
12 5    9
13 5    9
14 NA   9
15 5    6
16 5   NA
17 5    9
18 7    9
19 7    9
20 NA  NA

Finding the row means for rows in df1 −

df2

## Output

      y1           y2           RowMeans
1   0.5896447    1.8711656    1.23040515
2   0.9310379    1.1159848    1.02351135
3   2.9883385    0.6290764    1.80870743
4   NA          -0.6323118   -0.63231175
5   1.4797316    NA           1.47973158
6   2.9883385   -0.1533375    1.41750051
7   0.9310379    1.8711656    1.40110175
8  -0.1495998    0.6290764    0.23973829
9   0.5896447    1.8711656    1.23040515
10  0.5896447    NA           0.58964468
11  2.9883385   -0.1533375    1.41750051
12  0.5896447   -0.6323118   -0.02133354
13  2.9883385    0.6290764    1.80870743
14 -0.1495998    1.8711656    0.86078292
15  1.4797316    1.8711656    1.67544859
16 -0.1495998   -0.6323118   -0.39095576
17 -0.1495998    0.6290764    0.23973829
18  2.9883385   -0.6323118    1.17801337
19  2.9883385   -0.1533375    1.41750051
20  2.9883385   -0.1533375    1.41750051

Updated on: 08-Feb-2021

5K+ Views