How to find the row median of columns having same name in R matrix?

R ProgrammingServer Side ProgrammingProgramming

To find the row median of columns having same name in R matrix, we can follow the below steps −

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

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

Example

Create the matrix

Let’s create a matrix as shown below −

M<-matrix(rpois(150,10),ncol=6)
colnames(M)<-c("C1","C1","C2","C2","C1","C2")
M

Output

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

      C1 C1 C2 C2  C1 C2
[1,]   7  2  7 13  4 10
[2,]  20  8 10  8 15 12
[3,]   8 11  6 19  9 11
[4,]  10 10  9  8  8  8
[5,]   7 17 10  9  9 10
[6,]   9 10  8  6 11 13
[7,]   8  7 10 11  7 13
[8,]   8 11 10 16  4  9
[9,]  12  8 13  7  8  9
[10,]  6  7  7 14 15 11
[11,]  9  6 17 12 12 13
[12,] 11  8  8 10 13  8
[13,]  9  9  9  8  6 10
[14,]  7 11 11  8 11 11
[15,] 13 13  9 10 10 12
[16,]  5 10  4 13 15  6
[17,]  8 10  6  8 12  3
[18,]  8  9 10  8  7  7
[19,] 14 14 14  8  3 11
[20,]  7 13 10  8  8  9
[21,]  7 10  8  5 15  9
[22,]  8  8  5  8 11 13
[23,]  9 13  4  9  6 19
[24,] 12 11  5  7  7  7
[25,] 14 12  8 10 12  4

Find the row median of columns having same name

Using tapply along with colnames and median function to find the row median of columns having same name in matrix M −

M<-matrix(rpois(150,10),ncol=6)
colnames(M)<-c("C1","C1","C2","C2","C1","C2")
t(apply(M,1, function(x) tapply(x,colnames(M),median)))

Output

      C1 C2
[1,]   4 10
[2,]  15 10
[3,]   9 11
[4,]  10  8
[5,]   9 10
[6,]  10  8
[7,]   7 11
[8,]   8 10
[9,]   8  9
[10,]  7 11
[11,]  9 13
[12,] 11  8
[13,]  9  9
[14,] 11 11
[15,] 13 10
[16,] 10  6
[17,] 10  6
[18,]  8  8
[19,] 14 11
[20,]  8  9
[21,] 10  8
[22,]  8  8
[23,]  9  9
[24,] 11  7
[25,] 12  8
raja
Updated on 12-Nov-2021 07:16:42

Advertisements