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.
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().
Most helpful comment
If you only know you want var in the front and don't care about the order of the rest, you can do
like that?