【问题标题】:Tidy evaluation when column names are stored in strings列名存储在字符串中时的整洁评估
【发布时间】:2017-12-27 19:23:42
【问题描述】:

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

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 进行非标准评估的首选方式发生了变化。所有以 _ 结尾的函数现已弃用,现在推荐使用 tidy 评估框架。

【问题讨论】:

标签: r dplyr tidyverse rlang


【解决方案1】:

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

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

【讨论】:

  • 正是我需要的,谢谢!我想这是一个非常常见的用例,不知道为什么“使用 dplyr 编程”小插图中没有提到 sym
猜你喜欢
  • 2019-02-28
  • 2020-04-28
  • 1970-01-01
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
相关资源
最近更新 更多