Selecting column in function without quoting.

Short version:
Can I make this:df %>% select({{datecol}}) %>% pull() shorter in a function without quoting (so not df[["datecol"]]?

Long version:
I need to select a column in a function without quoting to fit in with an existing function. I am writing some error checking in to the function and am currently using {{ then pulling the column. Is there a better way of doing this? I am aware that I could use things like dataset[[date_col]] if I quoted the column.


# test data
df <- tibble(date = c(ymd("20210101"), ymd("20210102")),
             date2 = c("20210101", "20210102"))

check_date <- function(dataset, date_col){
  # need more efficient way to get the column here
  if (!is.Date(dataset %>% 
                          select({{date_col}}) %>% 
    rlang::abort(paste0("STOP!!!!")) # change later
  dataset # output - not important here, but things get done in the function to the initial dataset.

check_date(df, date) # correct column
check_date(df, date2) # should generate an error

Thanks. I guess that works, though I wouldn't want to use all the columns as the function will only take one column.

I think what I am after is if there is a cleaner way of doing this, without quoting the column, but it doesn't need an answer.

df %>% select({{datecol}}) %>% pull()

Thanks for your work on this @technocrat, but you are focusing on the wrong thing.

First of all, the question isn't that important as the code already works; I just want to know if I can make it shorter. I am writing error checks in to functions in a package.

I am actually interested in knowing if this bit: dataset %>% select({{date_col}}) %>% pull() could be done in a shorter way, but without quoting the column name. This is input to the error generating bit. I want to check if the column is a date, and if so, continue on the function, otherwise produce a message.

No, the function takes in only one column that the user specifies. It does not need to check all columns.

check_date <- function(dataset, date_col)

In the real function, there are other arguments, but it is still only one date argument. I don't want to print the dates. That bit was just in the example as output but I will edit that.

The select is superfluous, you can do this with only the pull

if (!is.Date(dataset %>% 
1 Like

Yes, that's it. Thanks.

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.