How to divide data.table object rows by number of columns in R?

R ProgrammingServer Side ProgrammingProgramming

To divide the row values by number of columns 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 number of columns.

Create the data frame

Let's create a data frame as shown below −

library(data.table)
x<-sample(0:9,25,replace=TRUE)
y<-sample(0:9,25,replace=TRUE)
DT<-data.table(x,y)
DT

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

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

Divide the data.table object row values by number of columns

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

library(data.table)
x<-sample(0:9,25,replace=TRUE)
y<-sample(0:9,25,replace=TRUE)
DT<-data.table(x,y)
DT_new<-t(apply(DT,1, function(x) x/length(x)))
DT_new

Output

      x   y
[1,] 2.0 2.0
[2,] 3.0 2.0
[3,] 3.0 2.0
[4,] 4.0 0.0
[5,] 0.5 3.0
[6,] 1.0 1.5
[7,] 4.0 4.5
[8,] 1.0 1.5
[9,] 1.5 3.5
[10,] 0.5 1.5
[11,] 1.0 4.5
[12,] 3.5 1.5
[13,] 0.5 0.0
[14,] 4.5 4.0
[15,] 2.5 3.0
[16,] 2.5 4.0
[17,] 0.0 0.0
[18,] 3.5 1.5
[19,] 3.0 3.5
[20,] 2.5 0.0
[21,] 0.5 1.5
[22,] 3.0 0.0
[23,] 2.5 4.0
[24,] 2.0 3.5
[25,] 0.5 0.5
raja
Published on 04-Aug-2021 11:29:10
Advertisements