Similar to my other question about double curly brackets within ggplot, I'm also struggling with using double curly brackets with filtering dates generally. In this function, users can specify a time period (week, month) and then the function filters based on the respective time period. For instance, selecting 'month' should cause the function to focus just on the Month
and Month_score
columns. However, it keeps failing and providing incorrect output:
Here's my sample data along with 2 attempts that I made:
#Sample data
library(dplyr)
library(lubdridate)
test <- tibble(Week = seq(as.Date("2014-09-04"), by = "week", length.out = 8),
Month = ymd(rep('2014-09-01', 4), rep('2014-10-01', 4)),
Week_score = c(2, 3, 4, 6, 5, 7, 8, 9),
Month_score = c(15, NA, NA, NA, 29, NA, NA, NA))
Attempt 1--no columns are removed (which is incorrect):
date_filter <- function(data, time_period = c("Week", "Month"), start_date = NA_Date_) {
data %>%
filter({{time_period}} > start_date)
}
date_filter(data = test, time_period = "Week", start_date = '2014-09-06')
Attempt 2: I explicitly callout that start_date is a date, but I get the below error
date_filter <- function(data, time_period = c("Week", "Month"), start_date = NA_Date_) {
data %>%
filter({{time_period}} > as.Date(start_date))
}
date_filter(data = test, time_period = "Week", start_date = '2014-09-06')