2

I have a dataframe with 9000 rows and 6 columns. I want to make the order of rows random i.e. some kind of shuffling to produce another dataframe with the same data but the rows in random order. Could anyone tell me how to do this in R?

Thanks

89_Simple
  • 3,393
  • 3
  • 39
  • 94

1 Answers1

2

If you want to sample (but keep) the same order of the rows then you can just sample the rows.

df <- data.frame(x=1:8, y=1:8, z=1:8)
df[sample(1:nrow(df)),]

which will produce

  x y z
2 2 2 2
3 3 3 3
4 4 4 4
6 6 6 6
5 5 5 5
8 8 8 8
7 7 7 7
1 1 1 1

If you rows should be sampled individually for each row then you can do something like

lapply(df, function(x) { sample(x)})

which results in

$x
[1] 3 1 4 6 5 2 8 7

$y
[1] 2 5 6 3 4 8 7 1

$z
[1] 6 1 8 3 2 7 4 5
ekstroem
  • 5,957
  • 3
  • 22
  • 48