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.
library(lubridate)
library(dplyr)
# 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}}) %>%
pull())
){
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 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.