列名存储在字符串中时的整洁评估

时间:2017-07-21 16:45:07

标签: r dplyr tidyverse rlang

我需要按逻辑列过滤表(或者更确切地说,通过它的否定),但列的名称可能会有所不同。当我事先知道他们的名字时,这很容易:

tb = tibble(
  id = 1:4, 
  col1 = c(TRUE, TRUE, FALSE, FALSE), 
  col2 = c(TRUE, FALSE, TRUE, FALSE)
)

tb
## # A tibble: 4 x 3
##      id  col1  col2
##   <int> <lgl> <lgl>
## 1     1  TRUE  TRUE
## 2     2  TRUE FALSE
## 3     3 FALSE  TRUE
## 4     4 FALSE FALSE

colname = quo(col1)

tb %>% 
  filter(!!colname) # rows where col1 is true
## # A tibble: 2 x 3
##      id  col1  col2
##   <int> <lgl> <lgl>
## 1     1  TRUE  TRUE
## 2     2  TRUE FALSE

tb %>% 
  filter(!(!!colname)) # rows where col1 is false
## # A tibble: 2 x 3
##      id  col1  col2
##   <int> <lgl> <lgl>
## 1     3 FALSE  TRUE
## 2     4 FALSE FALSE

colname = quo(col2)

tb %>% 
  filter(!!colname) # rows where col2 is true
## # A tibble: 2 x 3
##      id  col1  col2
##   <int> <lgl> <lgl>
## 1     1  TRUE  TRUE
## 2     3 FALSE  TRUE

tb %>% 
  filter(!(!!colname)) # rows where col2 is false
## # A tibble: 2 x 3
##      id  col1  col2
##   <int> <lgl> <lgl>
## 1     2  TRUE FALSE
## 2     4 FALSE FALSE
但是,我不能弄清楚当列名存储在字符串中时如何做同样的事情。例如:

colname = "col1"
tb %>% 
  filter(!!colname) 
## Error in filter_impl(.data, quo): Argument 2 filter condition does not evaluate to a logical vector

colname = quo("col1")
tb %>% 
  filter(!!colname)
## Error in filter_impl(.data, quo): Argument 2 filter condition does not evaluate to a logical vector

colname = quo(parse(text = "col1"))
tb %>% 
  filter(!!colname) 
## Error in filter_impl(.data, quo): Argument 2 filter condition does not evaluate to a logical vector

所以,问题是,我应该怎么做?

编辑:这不是this question的重复,因为从那时起,使用dplyr进行非标准评估的首选方式已发生变化。所有在_中终止的函数现已弃用,现在建议使用整洁的评估框架。

1 个答案:

答案 0 :(得分:6)

我们可以使用sym中的rlang来评估字符串

library(rlang)
library(dplyr)
colname <- "col1"

tb %>% 
    filter(!!sym(colname))
# A tibble: 2 x 3
#     id  col1  col2
#  <int> <lgl> <lgl>
#1     1  TRUE  TRUE
#2     2  TRUE FALSE