Reputation: 20329
I want to select certain columns in a data.frame
with the select
function from library(dplyr)
. The columns are given in a vector and I can use one_of()
to do so:
library(dplyr)
ddf <- data.frame(A = 1:2, B = 2:1, C = LETTERS[1:2])
sel <- c("A", "C")
ddf %>% select(one_of(sel))
# A C
# 1 1 A
# 2 2 B
I also can use also the form -one_of(.)
to select everything but the given columns:
ddf %>% select(-one_of(sel))
# B
# 1 2
# 2 1
But if I try to combine both, I get an unexpected result:
ddf %>% select(-one_of(sel), one_of(sel)) # works as expected
# B A C
# 1 2 1 A
# 2 1 2 B
ddf %>% select(one_of(sel), -one_of(sel)) ## does not work as expected
# data frame with 0 columns and 2 rows
Is this behaviour intentional? And how can I bring my columns into a certain order with select
without negating sel
that is sel <- "B"
would not be an option ;)
Upvotes: 3
Views: 790
Reputation: 20329
As proposed by @[David Arenburg] the solution is to use:
ddf %>% select(one_of(sel), everything())
Upvotes: 2