- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to divide data.table object rows by number of columns in R?
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
- Related Articles
- How to divide data frame rows by number of columns in R?
- How to divide matrix rows by number of columns in R?
- How to divide data.table object rows by row median in R?
- How to divide data frame rows in R by row minimum?
- How to divide data frame rows in R by row maximum?
- How to divide the data.table object rows in R by row minimum?
- How to divide the data.table object rows in R by row maximum?
- How to divide rows in a data.table object by row variance in R?
- How to divide the data.table object rows by row standard deviation in R?
- How to divide the data frame rows in R by row standard deviation?
- How to divide all columns by one column and keeping original data in R?
- How to divide matrix rows in R by row median?
- How to divide data.table object rows by maximum value in each row excluding 0 in R?
- How to divide columns of a matrix by vector elements in R?
- How to filter rows by excluding a particular value in columns of the R data frame?

Advertisements