I would like to both drop and reorder some features in a data frame in the same select() call if possible. As opposed to select(-var_to_drop) %>% select(var_I_want_first, everything()) can this be done in the same call?
E.g. with the diamonds dataset, suppose I want to drop the carat field, make price the first field and then keep everything() after that in it's same order? Tried:
library(tidyverse)
diamonds %>% select(-carat, price, everything()) # keeps carat
diamonds %>% select_at(vars(-carat, price, everything())) # also keeps carat?
Desired outcome is:
# desired outcome with multiple select() calls, want to do it in one:
diamonds %>% select(-carat) %>% select_at(vars(price, everything()))
# A tibble: 53,940 x 9
price cut color clarity depth table x y z
<int> <ord> <ord> <ord> <dbl> <dbl> <dbl> <dbl> <dbl>
1 326 Ideal E SI2 61.5 55 3.95 3.98 2.43
2 326 Premium E SI1 59.8 61 3.89 3.84 2.31
3 327 Good E VS1 56.9 65 4.05 4.07 2.31
4 334 Premium I VS2 62.4 58 4.2 4.23 2.63
5 335 Good J SI2 63.3 58 4.34 4.35 2.75
6 336 Very Good J VVS2 62.8 57 3.94 3.96 2.48
7 336 Very Good I VVS1 62.3 57 3.95 3.98 2.47
8 337 Very Good H SI1 61.9 55 4.07 4.11 2.53
9 337 Fair E VS2 65.1 61 3.87 3.78 2.49
10 338 Very Good H VS1 59.4 61 4 4.05 2.39
Can I get my desired result in a single call to select?
We can specify the columns to be removed after everything()
library(dplyr)
diamonds %>%
select(price, everything(), -carat)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With