How to divide data.table object rows by row median in R?

R ProgrammingServer Side ProgrammingProgramming

To divide the row values by row median in R’s data.table object, we can follow the below steps −

  • First of all, create a data.table object.
  • Then, use apply function to divide the data.table object row values by row median.

Create the data.table object

Let's create a data frame as shown below −

> library(data.table)
> x<-rpois(25,5)
> y<-rpois(25,2)
> z<-rpois(25,10)
> DT<-data.table(x,y,z)
> DT

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

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

Divide the data.table object row values by row median

Using apply function to divide the row values of DT by row median −

> library(data.table)
> x<-rpois(25,5)
> y<-rpois(25,2)
> z<-rpois(25,10)
> DT<-data.table(x,y,z)
> DT_new<-t(apply(DT,1, function(x) x/median(x)))
> DT_new

Output

x y z
[1,] 1.6666667 1.0000000 0.6666667
[2,] 0.3333333 1.0000000 2.3333333
[3,] 1.0000000 0.0000000 2.1666667
[4,] 1.0000000 0.3333333 1.6666667
[5,] 1.0000000 0.1250000 1.1250000
[6,] 1.0000000 0.1111111 1.1111111
[7,] 1.0000000 0.2500000 2.5000000
[8,] 1.0000000 0.2857143 1.7142857
[9,] 0.6000000 1.0000000 1.6000000
[10,] 1.0000000 0.4000000 1.4000000
[11,] 1.0000000 0.3333333 1.2222222
[12,] 1.0000000 0.6666667 2.6666667
[13,] 1.0000000 0.3333333 3.3333333
[14,] 1.0000000 0.6666667 3.3333333
[15,] 1.0000000 1.0000000 7.0000000
[16,] 1.0000000 0.3333333 1.6666667
[17,] 0.7500000 1.0000000 1.5000000
[18,] 1.0000000 0.5000000 2.7500000
[19,] 1.0000000 0.0000000 1.3333333
[20,] 1.0000000 0.6000000 1.8000000
[21,] 1.0000000 0.5000000 1.0000000
[22,] 1.0000000 0.7500000 3.0000000
[23,] 1.0000000 1.0000000 3.0000000
[24,] 1.0000000 0.1428571 2.1428571
[25,] 1.0000000 0.2000000 2.0000000
raja
Published on 03-Aug-2021 09:36:19
Advertisements