вставить оператор if после канала%>%, чтобы вернуть сообщение об ошибке в пользовательской функции - PullRequest
2 голосов
/ 10 октября 2019

Очень простая проблема, но не могу найти решение, все, что я хочу сделать, это вернуть сообщение об ошибке из функции, если переменная не имеет определенного class в dplyr канале. Допустим, у меня есть:

    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

и небольшая функция для построения гистограммы дат:

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))
  }

это прекрасно работает, если у меня есть переменная даты:

hist_date_fun(data1, date1)

Я просто хочу вставить оператор if и return ошибку в середине функции, чтобы сообщить пользователю, что переменная не является датой, что-то вроде:

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
}

, чтобыhist_date_fun(data1, num1) вернет ошибку.

Моя попытка:

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))
      }}

Любые предложения, пожалуйста?

Ссылка: https://community.rstudio.com/t/return-on-conditional-from-the-middle-of-a-pipe/5513/2

1 Ответ

2 голосов
/ 10 октября 2019

Вот один из способов использования оператора curly - curly из rlang

library(tidyverse)
library(rlang)
library(scales)

hist_date_fun <- function(df, date_varaible) {
    class_date <- df %>% pull({{date_varaible}}) %>% class
    if (class_date != "Date")
       stop("Stop variable is of class ", class_date)
     else {
      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() + 
         (axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
  }
}

hist_date_fun(data1, num1)

Ошибка в hist_date_fun (data1, num1): переменная Stop имеет целочисленный класс

...