How to divide data.table object rows by maximum value in each row excluding 0 in R?

R ProgrammingServer Side ProgrammingProgramming

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

  • First of all, create a data.table object.
  • Then, use apply function and if else function to divide the data.table object row values by row maximum excluding 0.

Create the data.table object

Let’s create a data.table object as shown below −

> library(data.table)
> x<-sample(0:5,25,replace=TRUE)
> y<-sample(0:5,25,replace=TRUE)
> z<-sample(0:5,25,replace=TRUE)
> 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:  2 0 3
2:  2 3 2
3:  0 1 3
4:  0 3 1
5:  1 5 2
6:  1 3 0
7:  4 5 2
8:  0 1 4
9:  4 2 0
10: 3 2 4
11: 1 4 3
12: 2 5 2
13: 4 2 0
14: 1 1 5
15: 1 2 4
16: 0 3 0
17: 4 1 1
18: 5 0 3
19: 2 0 4
20: 4 5 3
21: 4 0 3
22: 3 0 1
23: 2 1 5
24: 0 1 2
25: 2 1 1
    x y z

Divide the data.table object row values by row maximum excluding 0

Using apply function to divide the row values of DT by row maximum excluding 0 −

> library(data.table)
> x<-sample(0:5,25,replace=TRUE)
> y<-sample(0:5,25,replace=TRUE)
> z<-sample(0:5,25,replace=TRUE)
> DT<-data.table(x,y,z)
> DT_new<-t(apply(DT,1, function(x) if (0 %in% x) x else x/max(x)))
> DT_new

Output

x y z
[1,] 2.0000000 0.00 3.0000000
[2,] 0.6666667 1.00 0.6666667
[3,] 0.0000000 1.00 3.0000000
[4,] 0.0000000 3.00 1.0000000
[5,] 0.2000000 1.00 0.4000000
[6,] 1.0000000 3.00 0.0000000
[7,] 0.8000000 1.00 0.4000000
[8,] 0.0000000 1.00 4.0000000
[9,] 4.0000000 2.00 0.0000000
[10,] 0.7500000 0.50 1.0000000
[11,] 0.2500000 1.00 0.7500000
[12,] 0.4000000 1.00 0.4000000
[13,] 4.0000000 2.00 0.0000000
[14,] 0.2000000 0.20 1.0000000
[15,] 0.2500000 0.50 1.0000000
[16,] 0.0000000 3.00 0.0000000
[17,] 1.0000000 0.25 0.2500000
[18,] 5.0000000 0.00 3.0000000
[19,] 2.0000000 0.00 4.0000000
[20,] 0.8000000 1.00 0.6000000
[21,] 4.0000000 0.00 3.0000000
[22,] 3.0000000 0.00 1.0000000
[23,] 0.4000000 0.20 1.0000000
[24,] 0.0000000 1.00 2.0000000
[25,] 1.0000000 0.50 0.5000000
raja
Published on 03-Aug-2021 09:33:14
Advertisements