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

Time:05-20

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' がありません 

CodePudding user response:

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

CodePudding user response:

Even though select takes unquoted strings and hence works with test(m), this is not the case for starts_with, i.e.

test2('m')
                     mpg
Mazda RX4           21.0
Mazda RX4 Wag       21.0
Datsun 710          22.8
  • Related