Home > database >  Requiring packages inside a function R
Requiring packages inside a function R

Time:03-17

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, 
              start=c(year(as.Date(start)),month(as.Date(start))),
              end=c(year(as.Date(end)),month(as.Date(end))),
              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")
  return(list)
}

Am I right?

Thanks in advance!

CodePudding user response:

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

CodePudding user response:

If you're using Roxygen, do it as @Matt said. If you're not, then you need to do this: list the packages you want in the Imports: list in your DESCRIPTION file, e.g.

Imports:  lubridate, dplyr

This guarantees that your package won't load without having those two packages available.

You also need to do one of the following:

List the imported functions in your NAMESPACE file, e.g.

importFrom(lubridate, year, month)

and then just use them as if they are locally defined, or use the :: prefix every time you call them, e.g.

lubridate::year(date)

I'm not sure how these two steps correspond to the Roxygen tags.

  • Related