[英]How to to avoid error message when an empty argument in dplyr::select function?
這是我的代碼:
empty <- ""
mtcars %>% select(mpg,empty)
Error in `select()`:
! Can't subset columns that don't exist.
✖ Column `` doesn't exist.
empty
的 object 是一個 for 循環的 output。 因此,如果空等於""
,我不需要 select 什么,但我得到下面的錯誤。
換句話說,我應該能夠 select 這樣的事情: 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.