dplyr r : selecting columns whose names are in an external vector

Viewed 1197

Purpose

Can I select columns using dplyr conditional that the column name is in an external vector. I have found some posts that explain how to subset the data frame using a vector of name, but I could not find one when some of the names in the vector do not exist in the data frame.

Example dataset

  library(tidyverse)
  library(tibble)
  library(data.table)
  
  col_names <- c('a', 'b', 'e')
  
  rename <- dplyr::rename
  select <- dplyr::select
  
  set.seed(10002)
  a <- sample(1:20, 1000, replace=T)
  
  set.seed(10003)
  b <- sample(letters, 1000, replace=T)
  
  set.seed(10004)
  c <- sample(letters, 1000, replace=T)
  
  
  data <-   
    data.frame(a, b, c) 
# I would like to choose a, b that are in col_names vector. 
3 Answers

We could use any_of with select

library(dplyr)
data %>%
     select(any_of(col_names))

-output

 a b
1  1 e
2  4 e
3 13 f
4  8 m
5 10 z
6  3 y
...

Here is one way to solve your problem:

data[names(data) %in% col_names]

#    a b
# 1  1 e
# 2  4 e
# 3 13 f
# 4  8 m
# 5 10 z
# 6  3 y
# ...

We may also use matches:

library(dplyr)
data %>% 
  select(matches(col_names)))

Output:

       a b    
   <int> <chr>
 1     1 e    
 2     4 e    
 3    13 f    
 4     8 m    
 5    10 z    
 6     3 y    
 7    19 g    
 8     7 f    
 9    12 f    
10    15 k    
# … with 990 more rows
Related