Very simple problem but cant find the solution, all I want to do is return an error message from a function if a variable is not of a certain class within a dplyr pipe. Lets say I have:
library(tidyverse)
library(scales)
library(ggplot2)
data1 <- data.frame(date1 = sample(seq(as.Date("2005-01-01"), as.Date('2018-01-01'), by="day"), 5),
num1 = 1:5)
data1
date1 num1
1 2008-10-20 1
2 2005-01-17 2
3 2014-03-19 3
4 2005-01-24 4
5 2014-01-21 5
and a small function to plot a histogram of dates:
hist_date_fun <- function(df, date_varaible) {
date_varaible = enquo(date_varaible)
df %>%
group_by(month = floor_date(!!date_varaible, "month")) %>%
dplyr::summarize(freq = n()) %>%
ggplot(aes(x = month, y = freq)) +
geom_bar(stat="identity") +
scale_x_date(labels = date_format("%m-%Y"), breaks = date_breaks ("1 month")) +
theme_bw() +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
}
this works fine if I have a date variable:
hist_date_fun(data1, date1)
I just want to insert an if statement and return an error in the middle of the function to tell the user the variable is not a date, something like:
test <- function(x) {
if(!is.Date(x)) {
stop('this function only works for date input!\n',
'You have provided an object of class: ', class(x)[1])
}
else ....#rest of code
}
so that hist_date_fun(data1, num1) will return the error.
My attempt:
hist_date_fun <- function(df, date_varaible) {
date_varaible = enquo(date_varaible)
df %>%
if (!is.Date(date_varaible)) {
stop("Stop variable is of class", class(date_varaible)[1])
#or return()?
}
else {
group_by(month = floor_date(!!date_varaible, "month")) %>%
dplyr::summarize(freq = n()) %>%
ggplot(aes(x = month, y = freq)) +
geom_bar(stat="identity") +
scale_x_date(labels = date_format("%m-%Y"), breaks = date_breaks ("1 month")) +
theme_bw() +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
}}
Any suggestions please?
Ref:https://community.rstudio.com/t/return-on-conditional-from-the-middle-of-a-pipe/5513/2