How to change the order of columns in an R data frame?
https://www.tutorialspoint.com/how-to-change-the-order-of-columns-in-an-r-data-frame
-
12-09-2020 - |
Question
How to change the order of columns in an R data frame?
Ordering columns might be required when we want to manipulate the data. Manipulation can have several reasons such as cross verification, visualisation, etc. We should also be careful when we change anything in the original data because that might affect our processing. To change the order of columns we can use the single square brackets.
Example
Consider the below data frame −
> set.seed(1) > Class<-letters[1:20] > Grade<-rep(c("A","B","C","D"),times=5) > Score<-sample(1:100,20,replace=TRUE) > df<-data.frame(Class,Grade,Score) > df Class Grade Score 1 a A 68 2 b B 39 3 c C 1 4 d D 34 5 e A 87 6 f B 43 7 g C 14 8 h D 82 9 i A 59 10 j B 51 11 k C 97 12 l D 85 13 m A 21 14 n B 54 15 o C 74 16 p D 7 17 q A 73 18 r B 79 19 s C 85 20 t D 37 > df<-df[, c("Grade","Class","Score")] > df Grade Class Score 1 A a 68 2 B b 39 3 C c 1 4 D d 34 5 A e 87 6 B f 43 7 C g 14 8 D h 82 9 A i 59 10 B j 51 11 C k 97 12 D l 85 13 A m 21 14 B n 54 15 C o 74 16 D p 7 17 A q 73 18 B r 79 19 C s 85 20 D t 37
If the column names are in an order as shown below −
> x1<-letters[1:20] > x2<-rep(c("A","B","C","D"),times=5) > x3<-sample(1:100,20,replace=TRUE) > df<-data.frame(x3,x2,x1) > df x3 x2 x1 1 44 A a 2 25 B b 3 70 C c 4 39 D d 5 51 A e 6 42 B f 7 6 C g 8 24 D h 9 32 A i 10 14 B j 11 2 C k 12 45 D l 13 18 A m 14 22 B n 15 78 C o 16 65 D p 17 70 A q 18 87 B r 19 70 C s 20 75 D t
Now we can use sort function to change the order as shown below −
> df[,sort(names(df))] x1 x2 x3 1 a A 44 2 b B 25 3 c C 70 4 d D 39 5 e A 51 6 f B 42 7 g C 6 8 h D 24 9 i A 32 10 j B 14 11 k C 2 12 l D 45 13 m A 18 14 n B 22 15 o C 78 16 p D 65 17 q A 70 18 r B 87 19 s C 70 20 t D 75
Advertisements
Not affiliated with Tutorialspoint