

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to randomize column values of a data.table object for all columns in R?
To randomize column values of a data.table object for all columns in R, we can follow the below steps −
- First of all, create a data.table object.
- Then, use sample function with lapply to randomize the columns of the data.table object.
Create the data frame
Let's create a data frame as shown below −
library(data.table) x<-rpois(20,5) y<-rpois(20,10) z<-rpois(20,8) 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: 6 7 7 2: 7 11 7 3: 7 16 6 4: 7 8 11 5: 7 12 7 6: 8 10 2 7: 7 9 4 8: 4 12 6 9: 5 13 9 10: 7 8 7 11: 8 10 7 12: 2 12 8 13: 3 6 4 14: 7 9 9 15: 2 9 9 16: 6 17 10 17: 6 3 8 18: 7 14 4 19: 6 10 8 20: 7 15 8
Randomize column values in the data.table object
Using lapply and sample function to randomize the column values of DT −
library(data.table) x<-rpois(20,5) y<-rpois(20,10) z<-rpois(20,8) DT<-data.table(x,y,z) DT[,lapply(.SD,sample)]
Output
x y z 1: 7 9 9 2: 8 13 6 3: 7 10 9 4: 7 15 4 5: 7 14 11 6: 7 10 7 7: 5 8 2 8: 4 12 7 9: 8 12 8 10: 6 6 7 11: 6 10 7 12: 6 7 7 13: 2 12 4 14: 7 11 6 15: 2 16 10 16: 7 8 8 17: 3 3 8 18: 7 9 9 19: 6 9 4 20: 7 17 8
- Related Questions & Answers
- How to randomize column values of a data.table object for a set of columns in R?
- How to repeat column values of a data.table object in R by number of values in another column?
- How to combine two columns of a data.table object in R?
- How to standardize multiple columns not all in data.table object in R?
- How to multiply vector values in sequence with columns of a data.table object in R?
- How to find the number of unique values for each column in data.table object in R?
- How to find the number of columns where all row values are equal in data.table object in R?
- How to add a column to data.table object in R?
- How to separate two values in single column in data.table object in R?
- How to standardize selected columns in data.table object in R?
- How to scale some columns in data.table object in R?
- How to find the mean of a column summarized by other column names and common values in those columns in data.table object in R?
- How to select of data.table based on substring of row values for a column in R?
- How to extract data.table columns using a vector of column numbers in R?
- How to subset a data.table object using a range of values in R?
Advertisements