How to find the mean of row values in an R data frame using dplyr?

R ProgrammingServer Side ProgrammingProgramming

The mean of row values can be found by using rowwise function of dplyr package along with the mutate function to add the new column of means in the data frame. The rowwise function actually helps R to read the values in the data frame rowwise and then we can use mean function to find the means as shown in the below examples.

Example1

Consider the below data frame:

Live Demo

> x1<-rpois(20,1)
> x2<-rpois(20,5)
> df1<-data.frame(x1,x2)
> df1

Output

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

Loading dplyr package and finding the mean of row values of data frame df1:

Example

> library(dplyr)
> df1%>%rowwise()%>%mutate(Mean=mean(c(x1,x2)))
# A tibble: 20 x 3
# Rowwise:

Output

 x1   x2  Mean
<int><int><dbl>
1 0 8 4
2 2 3 2.5
3 2 5 3.5
4 0 5 2.5
5 3 2 2.5
6 0 10 5
7 3 5 4
8 1 7 4
9 0 4 2
10 1 6 3.5
11 1 2 1.5
12 1 6 3.5
13 1 1 1
14 0 7 3.5
15 3 3 3
16 1 5 3
17 0 5 2.5
18 0 4 2
19 0 7 3.5
20 0 8 4

Example2

Live Demo

> y1<-rnorm(20)
> y2<-rnorm(20,0.05)
> y3<-rnorm(20,0.5,0.0025)
> df2<-data.frame(y1,y2,y3)
> df2

Output

       y1         y2          y3
1 1.904146103 -1.010755257 0.4977748
2 -0.659153462 0.757833514 0.5000584
3 -1.349287399 0.035455534 0.4995245
4 1.251468999 -0.770912867 0.5023573
5 0.558542205 0.938371389 0.5037919
6 -1.088022365 -0.676129238 0.5024196
7 0.777812404 -0.649474781 0.4978783
8 -0.070005581 1.296222134 0.4989934
9 0.955297951 -0.010204761 0.5009613
10 -1.027516169 0.688293380 0.4995052
11 -0.004430055 1.095789444 0.5038756
12 -0.487932801 1.891399000 0.5006688
13 2.552820247 -0.240468655 0.4998481
14 -0.202030666 0.990596084 0.5025346
15 0.275771430 1.274736854 0.4984426
16 -0.541683198 1.056570340 0.4992698
17 -0.468355466 -1.878586227 0.4999905
18 0.031146373 0.009999742 0.5042049
19 0.608943200 -1.306773821 0.5030888
20 0.299916589 -0.759283709 0.5013502

Finding the mean of row values of data frame df2:

Example

> df2%>%rowwise()%>%mutate(Mean=mean(c(y1,y2,y3)))
# A tibble: 20 x 4
# Rowwise:

Output

  y1   y2   y3 Mean
<dbl><dbl><dbl><dbl>
1 1.90 -1.01 0.498 0.464
2 -0.659 0.758 0.500 0.200
3 -1.35 0.0355 0.500 -0.271
4 1.25 -0.771 0.502 0.328
5 0.559 0.938 0.504 0.667
6 -1.09 -0.676 0.502 -0.421
7 0.778 -0.649 0.498 0.209
8 -0.0700 1.30 0.499 0.575
9 0.955 -0.0102 0.501 0.482
10 -1.03 0.688 0.500 0.0534
11 -0.00443 1.10 0.504 0.532
12 -0.488 1.89 0.501 0.635
13 2.55 -0.240 0.500 0.937
14 -0.202 0.991 0.503 0.430
15 0.276 1.27 0.498 0.683
16 -0.542 1.06 0.499 0.338
17 -0.468 -1.88 0.500 -0.616
18 0.0311 0.0100 0.504 0.182
19 0.609 -1.31 0.503 -0.0649
20 0.300 -0.759 0.501 0.0140
raja
Published on 23-Nov-2020 10:50:11
Advertisements