Priority score when column names are stored in rows

I need to filter the table by a logical column (more precisely, by negating it), but the column name may be different. It is easy when I know their names in advance:

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

I could not, however, figure out how to do the same when the column names are stored in rows. For instance:

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

So the question is, how do I do this?

Edit: This is not a duplicate of this question , because since the preferred way to perform a non-standard evaluation with dplyr, all functions ending with _ are now deprecated, and it is now recommended to use a neat evaluation scheme.

+4
source share
1

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
+5

Source: https://habr.com/ru/post/1681985/


All Articles