Search code examples
rdplyrtidyverserlangcurly-braces

What if I want to use embracing operator with `starts_with()`?


Using the embracing operator eliminates the need to enclose arguments passed to a function in double quotation marks.

But what if I want to use it with starts_with()?

# This works.
test <- function(var) {
  mtcars |>
    dplyr::select({{ var }})
}
test(mpg) |> head()
#>                    mpg
#> Mazda RX4         21.0
#> Mazda RX4 Wag     21.0
#> Datsun 710        22.8
#> Hornet 4 Drive    21.4
#> Hornet Sportabout 18.7
#> Valiant           18.1

# But this won't work.
test2 <- function(var) {
  mtcars |>
    dplyr::select(starts_with({{ var }}))
}

test2(m) |> head()
#> Error in `dplyr::select()`:
#> !  オブジェクト 'm' がありません 

Solution

  • Try the following code:

    library(dplyr)
    
    test2 <- function(var) {
      x <- deparse(substitute(var))
      mtcars |> select(starts_with(x))
    }
    test2(m) |> head()
    

    Output:

                       mpg
    Mazda RX4         21.0
    Mazda RX4 Wag     21.0
    Datsun 710        22.8
    Hornet 4 Drive    21.4
    Hornet Sportabout 18.7
    Valiant           18.1