Search code examples
rpiper-packagemagrittr

How do I import "%>%" when writing an R package?


I'm running into the following error when loading an R package I'm writing.

Error in nations %>% rvest::html_nodes(".x") %>% rvest::html_nodes(".y") %>%  : 
  could not find function "%>%"

I'm not sure how to import this in my R package. This is how I have my function setup

 nations_url_odd<-nations %>%
    rvest::html_nodes('.x') %>%
    rvest::html_nodes('.y') %>%
    rvest::html_nodes('a')

Solution

  • Create a reexports.R file in your package with the following lines:

    #' @importFrom magrittr %>%
    #' @export
    magrittr::`%>%`
    

    This will make the pipe available to your package and also reexport it to users of your package, so when they load or attach your package the pipe will be available to them (they won’t have to also load magrittr). This can be automated with usethis::use_pipe() (see https://usethis.r-lib.org/reference/use_pipe.html). As @user2554330 mentions below, this solution depends on the use of roxygen2.