column names as variables in dplyr: select v filter

I am passing a variable to a function that identifies the column name to filter on.
I understand embrace {{}} that will resolve variables to actual names

The select statements below work as expected.

select(data,{{var}})

But the filter statements do not in this format

filter(data, {{var}} == "STRING")

Reprex:

The example reflects the data I am dealing with where the Column name will appear as values in the column.
Note the the last line and the error message that suggests colName does get resolved.

suppressMessages(library(tidyverse))

data <- tribble(
  ~NAME, ~Value,
  "NAME", 1,
  "NOTNAME", 2,
  "NAME", 3,
  "NOTNAME", 4,
  
)

colName = "NAME"

# both give same result
select(data,NAME)
select(data,{{colName}})
select(data,NAME) == select(data,{{colName}})

#these give different results
filter(data,NAME == colName)
filter(data, {{colName}} == colName)
filter(data, {{colName}} == "NAME")

# Error message suggests the {{colName}} gets resolved ok
filter(data,NAME == colName) == filter(data, {{colName}} == colName)

I walk around is to use get()

library(tidyverse)

data <- tribble(
    ~NAME, ~Value,
    "NAME", 1,
    "NOTNAME", 2,
    "NAME", 3,
    "NOTNAME", 4,
    
)

colName = "NAME"

filter(data, get({{colName}}) == colName)
#> # A tibble: 2 × 2
#>   NAME  Value
#>   <chr> <dbl>
#> 1 NAME      1
#> 2 NAME      3

Created on 2022-06-18 by the reprex package (v2.0.1)

1 Like

Many thanks. :grinning:

Never heard of get().
And reading

?get

I would never had worked out that it was the solution.

Still not sure I understand what get() does.

But yes it seems to work.

Also I found this works - not sure which is best

colName = "NAME"
colSym <- rlang::sym(colName)
filter(data, !!colSym == colName)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.