
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Divide Data Table Object Rows in R by Row Maximum
To divide the row values by row maximum 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 maximum.
Create the data frame
Let's create a data frame as shown below −
library(data.table) x<-rpois(25,5) y<-rpois(25,10) 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: 6 6 2: 8 14 3: 3 10 4: 5 8 5: 7 6 6: 5 13 7: 6 10 8: 0 12 9: 1 9 10: 5 7 11: 11 14 12: 7 14 13: 4 8 14: 1 9 15: 7 13 16: 2 12 17: 5 5 18: 5 8 19: 1 12 20: 2 7 21: 5 17 22: 6 7 23: 3 11 24: 5 12 25: 5 12 x y
Divide the data.table object row values by row maximum
Using apply function to divide the row values of DT by row maximum −
library(data.table) x<-rpois(25,5) y<-rpois(25,10) DT<-data.table(x,y) DT_new<-t(apply(DT,1, function(x) x/max(x))) DT_new
Output
x y [1,] 1.00000000 1.0000000 [2,] 0.57142857 1.0000000 [3,] 0.30000000 1.0000000 [4,] 0.62500000 1.0000000 [5,] 1.00000000 0.8571429 [6,] 0.38461538 1.0000000 [7,] 0.60000000 1.0000000 [8,] 0.00000000 1.0000000 [9,] 0.11111111 1.0000000 [10,] 0.71428571 1.0000000 [11,] 0.78571429 1.0000000 [12,] 0.50000000 1.0000000 [13,] 0.50000000 1.0000000 [14,] 0.11111111 1.0000000 [15,] 0.53846154 1.0000000 [16,] 0.16666667 1.0000000 [17,] 1.00000000 1.0000000 [18,] 0.62500000 1.0000000 [19,] 0.08333333 1.0000000 [20,] 0.28571429 1.0000000 [21,] 0.29411765 1.0000000 [22,] 0.85714286 1.0000000 [23,] 0.27272727 1.0000000 [24,] 0.41666667 1.0000000 [25,] 0.41666667 1.0000000
Advertisements