Skip to content

Instantly share code, notes, and snippets.

@djhocking
Last active February 28, 2022 19:08
Show Gist options
  • Save djhocking/62c76e63543ba9e94ebe to your computer and use it in GitHub Desktop.
Save djhocking/62c76e63543ba9e94ebe to your computer and use it in GitHub Desktop.
Select columns by vector of names using dplyr
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
@gregmacfarlane
Copy link

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