这是我的代码:
empty <- ""
mtcars %>% select(mpg,empty)
Error in `select()`:
! Can't subset columns that don't exist.
✖ Column `` doesn't exist.
empty
对象是for循环的输出。因此,如果empty =""
,我不需要选择什么,但我得到下面的错误。
换句话说,我应该能够选择这样的东西:mtcars %>% select(mpg,)
。我需要将""
转换为
如何避免这个错误?
可能使用tidyselect::any_of
library(dplyr)
empty <- ""
vars_select = c(empty, "mpg")
mtcars %>% select(any_of(vars_select))
或者创建一个新变量,如果它是一个空字符串,将其设置为NULL
:
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