thothal
thothal

Reputation: 20329

Pass vector of unquoted column names to a function and use first element

This works as expected:

library(dplyr)

f <- function(x = c(am, vs)) 
  mtcars %>% 
    select({{x}})

How would I rewrite the function (let's call it f2) such that f2 selects only the first element of x, that is f2() should eventually be the same as mtcars %>% select(am)?

Some requirements:

Upvotes: 9

Views: 252

Answers (2)

I_O
I_O

Reputation: 6911

Another approach:

f2 <- function(x = c(am, vs)){
  mtcars |> select({{x}}) |> select(1)
}

Upvotes: 2

lroha
lroha

Reputation: 34441

tidyselect::eval_select() returns a vector of indices used by select() that can be subset, so one approach might be:

library(tidyselect)
library(dplyr)

f2 <- function(x = c(am, vs)){
  mtcars %>%
    select(first(eval_select(expr({{x}}), data = .)))
}

f2() |>
  names()

[1] "am"

Upvotes: 11

Related Questions