Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to control the position of columns in a dataframe?

I have this dataframe

df = data.frame(x = 1:5,
                y = 6:10,
                z = 11:15,
                o = 16:20,
                m = 21:25)

And I want to change the position of columns in a simple way as follows :

1st column : m

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2st column : z

3st column : o

4st column : x

5st column : y

How can we do that with a simple function ? Thanks.

>Solution :

You can do

df[c(5, 3, 4, 1, 2)]

or

df[c('m', 'z', 'o', 'x', 'y')]

or

df |> with(data.frame(m, z, o, x, y))

or if you are using dplyr

df %>% select(m, z, o, x, y)

All of which result in

   m  z  o x  y
1 21 11 16 1  6
2 22 12 17 2  7
3 23 13 18 3  8
4 24 14 19 4  9
5 25 15 20 5 10
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading