How to change the order of one column data frame and get the output in data frame format in R?


To change the order of one column data frame and get the output in data frame format in R, we can follow the below steps −

  • First of all, create a data frame.
  • Then, use order function to change the order of column with drop argument set to FALSE

Create the data frame

Let's create a data frame as shown below −

 Live Demo

> x<-rnorm(20)
> df<-data.frame(x)
> df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

             x
1  -0.13734270
2  -1.02796577
3   1.40171778
4  -0.45367796
5   0.06634050
6  -1.27974403
7  -0.37548120
8   1.14533286
9   0.63468234
10 -0.25081200
11 -1.33503444
12  1.61475941
13 -0.23285412
14  0.47466024
15  0.85957117
16  0.61110128
17 -1.35330301
18 -0.73807621
19  0.10654000
20  0.07606264

Change the order of column

Example

Using order function with drop argument to change the order of column and return the output in data frame format −

 Live Demo

> x<-rnorm(20)
> dflt;-data.frame(x)
> df[order(df$x),,drop=FALSE]

Output

         x
17 -1.35330301
11 -1.33503444
 6 -1.27974403
 2 -1.02796577
18 -0.73807621
 4 -0.45367796
 7 -0.37548120
10 -0.25081200
13 -0.23285412
 1 -0.13734270
 5  0.06634050
20  0.07606264
19  0.10654000
14  0.47466024
16  0.61110128
 9  0.63468234
15  0.85957117
 8  1.14533286
 3  1.40171778
12  1.61475941

Updated on: 13-Aug-2021

96 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements