[SOLVED] Requiring packages inside a function R


I have a question, I am making a package in R (just for me).

So I am scripting my function sets and inside sets I use a lot of dplyr functions.

How can I make that if you’re gonna use my package you must have dplyr.

I think is with require() inside the function? I was reading about this function and got more confused.

I was thinking it should go like this:

sets <- function(base, start, end, f_hor, freq=12){
  require(dplyr, lubridate)
  train <- base %>% 
    filter(year(date)>=as.Date(start)) %>% 
    filter(year(date)<=as.Date(end)) %>% select(-date)
  train <- ts(train, 
              frequency = freq)

  test <- base %>% 
    filter(year(date)<as.Date(end)) %>% select(-date)
  test <- head(test, f_hor)
  list <- list(train, test)
  names(list) <- c("train", "test")

Am I right?

Thanks in advance!


You would likely want to include it in your roxygen skeleton at the top of your function using the @import tag. You could also consider using @importFrom

Something like:

#' My function called sets
#' @param base ...
#' @param start
#' @param end
#' @param f_hor
#' @param freq
#' @return a list...
#' @import dplyr
#' @import lubridate
#' @importFrom lubridate year month
#' @export
sets <- function(base, start, end, f_hor, freq = 12){

Additionally, within your function, you can opt to explicitly call a function from a specific package, i.e:

sets <- function(base, start, end, f_hor, freq = 12){
  train <- base %>% 
    dplyr::filter(lubridate::year(date)>=as.Date(start)) %>% 
    dplyr::filter(lubridate::year(date)<=as.Date(end)) %>% select(-date)

Answered By – Matt

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *