【发布时间】:2017-11-28 02:55:50
【问题描述】:
假设我们有一个字符向量 cols_to_select,其中包含我们要从数据框 df 中选择的一些列,例如
df <- tibble::data_frame(a=1:3, b=1:3, c=1:3, d=1:3, e=1:3)
cols_to_select <- c("b", "d")
假设我们还想使用dplyr::select,因为它是使用%>% 的操作的一部分,所以使用select 使代码易于阅读。
似乎有多种方法可以实现这一目标,但有些方法比其他方法更强大。请你能告诉我哪个是“正确”的版本,为什么?或者也许还有其他更好的方法?
dplyr::select(df, cols_to_select) #Fails if 'cols_to_select' happens to be the name of a column in df
dplyr::select(df, !!cols_to_select) # i.e. using UQ()
dplyr::select(df, !!!cols_to_select) # i.e. using UQS()
cols_to_select_syms <- rlang::syms(c("b", "d")) #See [here](https://stackoverflow.com/questions/44656993/how-to-pass-a-named-vector-to-dplyrselect-using-quosures/44657171#44657171)
dplyr::select(df, !!!cols_to_select_syms)
附言我意识到这可以在基础 R 中使用 df[,cols_to_select]
【问题讨论】:
-
作为替代使用 .vars 参数:
select_at(df, .vars = cols_to_select)
标签: r dplyr tidyverse rlang tidyeval