选择列,如果列不存在则跳过

时间:2018-02-12 14:32:25

标签: r select dplyr

我想通过选择列来制作我的数据的子集,如下所示:

select(df, col1, col2, col3, col4) 

但有时我的数据集略有不同,只有col1,col2和col4。

如何使用select(),如果列不存在,它会继续而不会出错?

因此,它将为col1,col2和col4(以及跳过col3)提供数据集。如果我只运行上面的select()行,我会收到此错误:

Error in overscope_eval_next(overscope, expr) : object 'col3' not found

2 个答案:

答案 0 :(得分:5)

df[, names(df) %in% c('col1', 'col2', 'col3', 'col4')]

答案 1 :(得分:3)

您可以使用dplyr中的one_of() select helper并将列名称作为字符串传递。它只会对不存在的列发出警告。


library(dplyr)

select(mtcars, one_of(c("mpg", "disp", "foo")))

#> Warning: Unknown variables: `foo`

#>                      mpg  disp
#> Mazda RX4           21.0 160.0
#> Mazda RX4 Wag       21.0 160.0
#> Datsun 710          22.8 108.0
#> Hornet 4 Drive      21.4 258.0
#> Hornet Sportabout   18.7 360.0
相关问题