- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to reorder the columns in an R data frame?
Reordering of columns can be done by using square brackets.
Example
> 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
Let’s say we want to change the order of columns as X3, X2, X4, and X1 then it can be done as shown below −
> 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
Advertisements