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

R ProgrammingServer Side ProgrammingProgramming

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 −

Example

df1$RowMeans<-rowMeans(df1,na.rm=TRUE)
df1

Output

   x1  x2  RowMeans
1  NA  2   2.0
2  7   9   8.0
3  5   8   6.5
4  7   NA   7.0
5  NA  8   8.0
6  7   8   7.5
7  5   2   3.5
8  5  NA   5.0
9  5   6   5.5
10 NA 8    8.0
11 7   8   7.5
12 5   9   7.0
13 5   9   7.0
14 NA 9    9.0
15 5  6    5.5
16 5  NA   5.0
17 5  9    7.0
18 7  9    8.0
19 7  9    8.0
20 NA NA   NaN

Example

 Live Demo

y1<-sample(c(NA,rnorm(5)),20,replace=TRUE)
y2<-sample(c(NA,rnorm(5)),20,replace=TRUE)
df2<-data.frame(y1,y2)
df2

Output

       y1        y2
1  0.5896447   1.8711656
2  0.9310379   1.1159848
3  2.9883385   0.6290764
4  NA          -0.6323118
5  1.4797316    NA
6  2.9883385   -0.1533375
7  0.9310379   1.8711656
8  -0.1495998   0.6290764
9  0.5896447   1.8711656
10  0.5896447   NA
11  2.9883385   -0.1533375
12  0.5896447   -0.6323118
13  2.9883385   0.6290764
14  -0.1495998   1.8711656
15  1.4797316   1.8711656
16 -0.1495998   -0.6323118
17  -0.1495998   0.6290764
18  2.9883385   -0.6323118
19  2.9883385   -0.1533375
20  2.9883385   -0.1533375

Finding the row means for rows in df2 −

Example

df2$RowMeans<-rowMeans(df2,na.rm=TRUE)
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
raja
Published on 08-Feb-2021 05:27:17
Advertisements