Suppose, we have the following dataframe.
1 2 3 4 5 |
Name <- c("John", "Max", "Nancy", "Paul", "Sandra") Major <- c("English", "Medicine", "Physics", "Chemistry", "Biology") Grade <- c("A","B","A","B","A") data <- data.frame(Name,Major,Grade) |
1 2 3 4 5 6 7 |
> data Name Major Grade 1 John English A 2 Max Medicine B 3 Nancy Physics A 4 Paul Chemistry B 5 Sandra Biology A |
We would like to change the order to major, grade, and name. We can achieve the result by the following methods
Method 1: Specifying a column name
1 |
data2 <- data[c("Major", “Grade", "Name")] |
1 2 3 4 5 6 7 |
> data2 Major Grade Name 1 English A John 2 Medicine B Max 3 Physics A Nancy 4 Chemistry B Paul 5 Biology A Sandra |
Method 2: Specifying a column number
1 |
data3 <- data[c(2,3,1)] |
1 2 3 4 5 6 7 |
> data3 Major Grade Name 1 English A John 2 Medicine B Max 3 Physics A Nancy 4 Chemistry B Paul 5 Biology A Sandra |
Method 3: Ascending/Descending Order
It will be even easier if we want to order the columns in ascending/descending order.
1 |
data4 <- data[,order(colnames(data),decreasing=TRUE)] |
1 2 3 4 5 6 |
Name Major Grade 1 John English A 2 Max Medicine B 3 Nancy Physics A 4 Paul Chemistry B 5 Sandra Biology A |