1

I would like to select columns if they are contained in a list. The problem is that I get an error for the columns that don't exist.

Try 1:

library(dplyr)

data(band_instruments)

desired_vars <- c("plays", "grade", "age")

is_desired_vars <- function(x) names(x) %in% desired_vars

band_instruments %>%
 select_if(.predicate = is_desired_vars)

Try 2:

desired_vars <- c("plays", "grade", "age")
band_instruments[, desired_vars]

More Details:

I would like the solution to generalize. There may be a dataframe that this function acts on which would contain all columns in the list, but some dataframes will not contain all of the columns in this list.

Alex
  • 2,603
  • 4
  • 40
  • 73
  • **band_instruments** data includes only 2 columns : *name , plays*. So you can't call it like `band_instruments[, desired_vars]` . If you call `band_instruments[, "plays"]` , you get an output. – maydin Aug 24 '19 at 21:21
  • The problem is that I would like the solution to generalize. There may be a dataframe that this function acts on which would contain all columns in the list, but some dataframes will not contain all of the columns in this list. – Alex Aug 24 '19 at 21:22
  • 2
    If you want to follow your setting, you can run : `band_instruments[,is_desired_vars(band_instruments)]` – maydin Aug 24 '19 at 21:24
  • 1
    That is exactly what I was going for. Thanks! – Alex Aug 24 '19 at 21:30

0 Answers0