# How to divide the data.table object rows in R by row minimum?

To divide the row values by row minimum 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 minimum.

## Create the data.table object

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

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

## Divide the data.table object row values by row minimum

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

> library(data.table)
> x<-sample(1:5,25,replace=TRUE)
> y<-sample(1:5,25,replace=TRUE)
> z<-sample(1:5,25,replace=TRUE)
> DT<-data.table(x,y,z)
> DT_new<-t(apply(DT,1, function(x) x/min(x)))
> DT_new

## Output

        x      y       z
[1,]  4.00 1.000000 3.000000
[2,]  4.00 3.000000  1.000000
[3,]  1.00 3.000000  5.000000
[4,]  1.00 5.000000  5.000000
[5,]  3.00 3.000000  1.000000
[6,]  1.00 1.000000  1.666667
[7,]  3.00 1.000000  4.000000
[8,]  2.00 1.000000  2.000000
[9,]  1.00 2.000000  5.000000
[10,] 5.00 1.000000  3.000000
[11,] 2.50 1.000000  2.500000
[12,] 1.50 2.500000  1.000000
[13,] 2.50 2.500000  1.000000
[14,] 3.00 1.000000  1.000000
[15,] 1.25 1.000000  1.250000
[16,] 2.00 1.000000  3.000000
[17,] 1.00 3.000000  3.000000
[18,] 1.00 2.000000  1.500000
[19,] 4.00 1.000000  4.000000
[20,] 1.00 1.000000  4.000000
[21,] 1.00 2.000000  1.000000
[22,] 1.00 1.000000  5.000000
[23,] 1.00 1.666667  1.000000
[24,] 1.00 1.000000  3.000000
[25,] 2.00 1.000000  2.000000

Updated on: 13-Aug-2021

73 Views