R:按列随机播放数据框

R: Shuffle dataframe columnwise

这个 link 回答了我的部分问题:How to randomize (or permute) a dataframe rowwise and columnwise?

> df1
  a b c
1 1 1 0
2 1 0 0
3 0 1 0
4 0 0 0

Column-wise shuffle 给出以下输出 df3,这是对列重新排序

> df3 <- df1[,sample(ncol(df1))]
> df3
  c a b
1 0 1 1
2 0 1 0
3 0 0 1
4 0 0 0

我想要的是列名也应该改变。按行和按列的总计保持不变,只是重新分配了列名。类似于 df4。我怎样才能做到这一点?

> df4
  c a b
1 1 1 0
2 1 0 0
3 0 1 0
4 0 0 0

PS:如何保持 df 的形状按列排列?当我 post 格式崩溃的问题时?

您可能只想对列名进行采样。类似于:

names(df) <- names(df)[sample(ncol(df))]