可以使用方括号对列进行重新排序。
> df = data.frame(matrix(rnorm(20), nrow=5)) > df X1 X2 X3 X4 1 -0.3637644 2.0770246 0.48763128 -0.09019256 2 -3.1758515 2.3173075 0.86846761 0.38396459 3 1.1844641 0.3412267 1.90986295 -1.03493074 4 -0.5953466 1.7211738 -0.90686896 -0.71215313 5 -0.8732530 0.3256303 0.02312328 -0.36993899
假设我们想将列的顺序更改为X3,X2,X4和X1,则可以如下所示进行操作-
> df[,c(3,2,4,1)] X3 X2 X4 X1 1 0.48763128 2.0770246 -0.09019256 -0.3637644 2 0.86846761 2.3173075 0.38396459 -3.1758515 3 1.90986295 0.3412267 -1.03493074 1.1844641 4 -0.90686896 1.7211738 -0.71215313 -0.5953466 5 0.02312328 0.3256303 -0.36993899 -0.8732530