Search code examples
rvariablespositionmultiple-columns

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

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