0

I want to randomly shuffle all columns in a data frame, except the 1st column. The 1st column should remain in its place.

So far I've only figured out how to shuffle all columns, but this includes the first column.

df <- data.frame(matrix(rnorm(20),nrow=5))
df <- df[,sample(ncol(df))]

Here, X1 should remain in its place while X2, X3 and X4 should be shuffled randomly.

> df
      X1         X2         X3         X4
1  0.2582514 -0.3615941  0.5114984 -0.6918975
2  1.8234944 -0.5024039  0.9252904 -1.0034840
3  0.1513888  0.1269615 -1.2987913 -0.7017240
4 -0.8194843  1.1256620  2.0126086  1.7089314
5 -0.6733888 -1.1731604 -0.1649225 -1.7343608

Any suggestions?

1 Answers1

2

Just exclude the first one:

df[, c(1, sample(2:ncol(df)))]
sgibb
  • 25,396
  • 3
  • 68
  • 74
  • Hi, do you know how your answer would change for the following question similar to this one? https://stackoverflow.com/questions/60687700/how-to-randomly-shuffle-a-populaiton-by-preserving-all-properites-except-one/60687757#60687757 – Rebel Mar 14 '20 at 23:54