How to randomize column values of a data.table object for all columns in R?

R ProgrammingServer Side ProgrammingProgramming

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
raja
Published on 07-Aug-2021 09:06:37
Advertisements