如何使用dplyr引用变量而不是列 [英] How to refer to variable instead of column with dplyr
本文介绍了如何使用dplyr引用变量而不是列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用dplyr:filter时,我经常计算一个保存可行选择的局部变量:
When using dplyr:filter, I often compute a local variable that holds the viable choices:
df <- as_tibble(data.frame(id=c("a","b"), val=1:6))
ids <- c("b","c")
filter(df, id %in% ids)
# giving id %in% c("b","c")
但是,如果偶然地数据集具有相同名称的列,则无法实现预期的目的:
However, if the dataset by chance has a column with the same name, this fails to achieve the intended purpose:
df$ids <- "a"
filter(df, id %in% ids)
# giving id %in% "a"
我应该如何显式引用ids变量而不是ids列?
How should I explicitly refer to the ids variable instead of the ids column?
推荐答案
用取消引号!
告诉 filter
在调用环境中查找而不是在数据框:
Unquote with !!
to tell filter
to look in the calling environment instead of the data frame:
library(tidyverse)
df <- data_frame(id = rep(c("a","b"), 3), val = 1:6)
ids <- c("b", "c")
df %>% filter(id %in% ids)
#> # A tibble: 3 x 2
#> id val
#> <chr> <int>
#> 1 b 2
#> 2 b 4
#> 3 b 6
df <- df %>% mutate(ids = "a")
df %>% filter(id %in% ids)
#> # A tibble: 3 x 3
#> id val ids
#> <chr> <int> <chr>
#> 1 a 1 a
#> 2 a 3 a
#> 3 a 5 a
df %>% filter(id %in% !!ids)
#> # A tibble: 3 x 3
#> id val ids
#> <chr> <int> <chr>
#> 1 b 2 a
#> 2 b 4 a
#> 3 b 6 a
当然,避免此类问题的更好方法是不要使用相同的名称全球环境中的向量。
Of course, the better way to avoid such issues is to not put identically-named vectors in your global environment.
这篇关于如何使用dplyr引用变量而不是列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文