Home > Net >  How to to avoid error message when an empty argument in dplyr::select function?
How to to avoid error message when an empty argument in dplyr::select function?

Time:11-22

This is my code:

empty <- ""

mtcars %>% select(mpg,empty)
Error in `select()`:
! Can't subset columns that don't exist.
✖ Column `` doesn't exist.

The empty object is an output of a for loop. So if empty is equal "" I wouldn't need to select nothing but I get the error bellow.

In other words, I should be able to select something like this: mtcars %>% select(mpg,) . I would need to transform "" to

How can I avoid this error?

CodePudding user response:

Perhaps using tidyselect::any_of

library(dplyr)

empty <- ""
vars_select = c(empty, "mpg")

mtcars %>% select(any_of(vars_select))

Or create a new variable and set it to NULL if it's an empty string:

library(dplyr)

empty <- ""

if (empty == "") {
    empty_var = NULL
}

mtcars %>% select(mpg, any_of(empty_var))
Mazda RX4           21.0
Mazda RX4 Wag       21.0
Datsun 710          22.8
Hornet 4 Drive      21.4
Hornet Sportabout   18.7
Valiant             18.1
Duster 360          14.3
Merc 240D           24.4
Merc 230            22.8
Merc 280            19.2
Merc 280C           17.8
Merc 450SE          16.4
Merc 450SL          17.3
Merc 450SLC         15.2
Cadillac Fleetwood  10.4
Lincoln Continental 10.4
Chrysler Imperial   14.7
Fiat 128            32.4
Honda Civic         30.4
Toyota Corolla      33.9
Toyota Corona       21.5
Dodge Challenger    15.5
AMC Javelin         15.2
Camaro Z28          13.3
Pontiac Firebird    19.2
Fiat X1-9           27.3
Porsche 914-2       26.0
Lotus Europa        30.4
Ford Pantera L      15.8
Ferrari Dino        19.7
Maserati Bora       15.0
Volvo 142E          21.4
  • Related