To find the row median of columns having same name in data.table object in R, we can follow the below steps −
First of all, create a data.table 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.
Let’s create a data.table as shown below −
library(data.table) DT<- data.table(x=rpois(25,5),y=rpois(25,10),x=rpois(25,5),y=rpois(25,2),x=rpois(25,4),y=rpo is(25,10),check.names=FALSE) DT
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x y x y x y 1: 4 15 6 1 6 9 2: 4 11 3 3 4 9 3: 1 6 8 2 2 12 4: 6 9 4 2 6 12 5: 8 10 1 1 2 9 6: 6 9 7 4 2 4 7: 8 8 3 2 1 8 8: 2 10 7 2 5 16 9: 7 5 8 1 5 9 10: 5 11 9 5 7 10 11: 3 4 1 5 6 6 12: 10 10 6 3 6 13 13: 7 5 4 2 3 8 14: 4 9 0 2 5 14 15: 6 11 8 2 4 10 16: 6 8 3 3 7 7 17: 7 8 4 2 1 8 18: 8 9 7 4 3 15 19: 4 16 5 1 3 7 20: 7 15 4 1 3 12 21: 6 10 5 1 1 9 22: 4 11 3 0 2 9 23: 4 12 4 3 4 17 24: 4 8 2 1 5 6 25: 5 9 1 0 2 5 x y x y x y
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 data.table object DT −
library(data.table) DT<- data.table(x=rpois(25,5),y=rpois(25,10),x=rpois(25,5),y=rpois(25,2),x=rpois(25,4),y=rpo is(25,10),check.names=FALSE) t(apply(DT,1, function(x) tapply(x,colnames(DT),median)))
x y [1,] 6 9 [2,] 4 9 [3,] 2 6 [4,] 6 9 [5,] 2 9 [6,] 6 4 [7,] 3 8 [8,] 5 10 [9,] 7 5 [10,] 7 10 [11,] 3 5 [12,] 6 10 [13,] 4 5 [14,] 4 9 [15,] 6 10 [16,] 6 7 [17,] 4 8 [18,] 7 9 [19,] 4 7 [20,] 4 12 [21,] 5 9 [22,] 3 9 [23,] 4 12 [24,] 4 6 [25,] 2 5