Last active
February 28, 2022 19:08
-
-
Save djhocking/62c76e63543ba9e94ebe to your computer and use it in GitHub Desktop.
Select columns by vector of names using dplyr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
one <- seq(1:10) | |
two <- rnorm(10) | |
three <- runif(10, 1, 2) | |
four <- -10:-1 | |
df <- data.frame(one, two, three) | |
df2 <- data.frame(one, two, three, four) | |
str(df) | |
names.df <- colnames(df) | |
names.df.2 <- c("one", "two", "three") | |
#install.packages("dplyr") | |
library(dplyr) | |
select_(df2, names.df) # no - only first variable name | |
select_(df2, names.df.2) # no - only first variable name | |
select(df2, one_of(names.df)) # success | |
select(df2, one_of(names.df.2)) # success |
I've read the vignette plenty of times and still don't understand .dots
, but this has helped me immensely.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From Hadley on twitter:
select_(df2, .dots = names.df)
see: vignette("nse") to understand more about .dots and select_