How to find the row mean of columns having same name in R data frame?

R ProgrammingServer Side ProgrammingProgramming

To find the row mean of columns having same name in R data frame, we can follow the below steps −

  • First of all, create a data frame with some columns having same name.

  • Then, use tapply along with colnames and mean function to find the row mean of columns having same name.

Example

Create the data frame

Let’s create a data frame as shown below −

df<-
data.frame(x=rpois(25,2),y=rpois(25,1),x=rpois(25,10),y=rpois(25,5),check.names=FALSE)
df

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

   x y  x  y
1  2 1 12  6
2  2 3  7  7
3  2 0 13  7
4  2 1  9  4
5  2 0 13  8
6  2 3 10  3
7  3 1  6  6
8  1 0  9  4
9  1 0 10  3
10 2 0 11  4
11 3 0 10  2
12 0 3  2 10
13 1 1 11  4
14 1 2  7  5
15 5 1  7  5
16 1 2  8  2
17 1 1 10 10
18 1 2 12  3
19 0 3 15  5
20 2 0 12  3
21 1 1 13  3
22 2 0  9  4
23 1 1  8  5
24 1 0  9  4
25 1 0  8  6

Find the row mean of columns having same name

Using tapply along with colnames and mean function to find the row mean of columns having same name in data frame df −

df<-
data.frame(x=rpois(25,2),y=rpois(25,1),x=rpois(25,10),y=rpois(25,5),check.names=FALSE)
t(apply(df,1, function(x) tapply(x,colnames(df),mean)))

Output

        x  y
[1,]  7.0 3.5
[2,]  4.5 5.0
[3,]  7.5 3.5
[4,]  5.5 2.5
[5,]  7.5 4.0
[6,]  6.0 3.0
[7,]  4.5 3.5
[8,]  5.0 2.0
[9,]  5.5 1.5
[10,] 6.5 2.0
[11,] 6.5 1.0
[12,] 1.0 6.5
[13,] 6.0 2.5
[14,] 4.0 3.5
[15,] 6.0 3.0
[16,] 4.5 2.0
[17,] 5.5 5.5
[18,] 6.5 2.5
[19,] 7.5 4.0
[20,] 7.0 1.5
[21,] 7.0 2.0
[22,] 5.5 2.0
[23,] 4.5 3.0
[24,] 5.0 2.0
[25,] 4.5 3.0
raja
Updated on 15-Nov-2021 06:52:01

Advertisements