- 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 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 Articles
- How to randomize column values of a data.table object for a set of columns in R?
- How to create a table of frequency for range of values in an R data frame column?
- How to create an ID column for the combination of values in multiple columns in R data frame?
- How to convert a data frame into table for two factor columns and one numeric column in R?
- How to create line chart for all columns of a data frame a in R?
- How to get the summary statistics including all basic statistical values for R data frame columns?
- How to divide all columns by one column and keeping original data in R?
- How to find standard deviations for all columns of an R data frame?
- How to print the exact values of all elements in a column of an R data frame?
- How to create a new column with means of row values for each or some of the columns in an R data frame?
- How to perform Wilcoxon test for all columns in an R data frame?
- How to perform shapiro test for all columns in an R data frame?
- How to repeat column values of a data.table object in R by number of values in another column?
- How to replace NA values in columns of an R data frame form the mean of that column?
- How to find the frequency table for factor columns in an R data frame?

Advertisements