4

I want to remove a column from a data frame only if it's there.

Example:

a <- 1:5
x <- tibble(a, b = a * 2, c = 1)
x %>% select(-'a')
x %>% select(-'d') # Throws an error

I want a way to remove columns a and d only if they exist, so a is removed and the attempt to remove d never happens. I tried modifying this solution to my problem, but I could not get it to work.

Phil
  • 7,287
  • 3
  • 36
  • 66
Forklift17
  • 2,245
  • 3
  • 20
  • 32

1 Answers1

1

data.table

library(data.table)
a <- 1:5
x <- data.frame(a, b = a * 2, c = 1)
cols <- c("a", "d")
my_cols <- intersect(cols, names(x))

setDT(x)[, ..my_cols]
#>    a
#> 1: 1
#> 2: 2
#> 3: 3
#> 4: 4
#> 5: 5

Created on 2021-07-09 by the reprex package (v2.0.0)

Yuriy Saraykin
  • 8,390
  • 1
  • 7
  • 14