Dplyr: Reorder variables in a data frame?

Created on 31 May 2015  路  7Comments  路  Source: tidyverse/dplyr

Is there a way to order variables using dplyr's functions? That is, I was looking for an equivalent function of Stata's order command.

An example data frame:

state = c("Alabama", "Alabama")
var = rnorm(2)
year = 2009:2010
df = dplyr::data_frame(state, var, year)

To reorder variables in df, one can use df = df[, c(state, year, var)]. But I was wondering if there is a dplyr single table verb to do the same thing.

Most helpful comment

select(df, year, var, state)   # reverses the columns

If you only know you want var in the front and don't care about the order of the rest, you can do

df %>%
  select(var, everything())

like that?

All 7 comments

select(df, year, var, state)   # reverses the columns

If you only know you want var in the front and don't care about the order of the rest, you can do

df %>%
  select(var, everything())

like that?

Excellent! Thank you!

Is this everything() a base R function? I can't find anything through ?everything and ??everything in my R Studio's console.

No problem!

everything() is in dplyr's select-utils.R. I don't think the documentation is exported, though.

Hi Hadley, @hadley
Why doesn't this support a variable at the end?

df %>%
    select(everything(), var)

Sometimes you need variables at the end to create tables.

@LiNk-NY
According to https://github.com/tidyverse/dplyr/issues/3051#issuecomment-324646580, you can do this instead:

df %>%
    select(-var, everything())

I guess so but this forces me to use two select calls:

df %>%
    select(-deleteme, -delete) %>%
    select(-var, everything())

Thanks!

IIUC, using two select() is unavoidable in your case since select() doesn't actually "select" columns but sorts when used with everything(). So, if you want to "select" + sort columns, there must be two select().

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ggrothendieck picture ggrothendieck  路  4Comments

Eli-Berkow picture Eli-Berkow  路  4Comments

bachlaw picture bachlaw  路  3Comments

JohnMount picture JohnMount  路  4Comments

DasHammett picture DasHammett  路  3Comments