R: use the magrittr pipe statement in a self-written package

I would like to use the pipe operator %>% provided in the magrittr package in the package that I wrote to myself to convert dplyr chains. magrittr appears as Import in the DESCRIPTION file. After downloading my own package and testing a function that uses a statement operator, I get the following error message:

Error in function name (parameter ,: could not find function "%>%"

Changing %>% to magrittr::%>% in the function source code does not help either because the package can no longer be created.

+47
namespaces r magrittr
Jan 14 '15 at 16:06
source share
3 answers

It should have worked correctly if you had the magrittr specified in Depends . However, this is not recommended . Instead, you leave magrittr in Imports and add the following line to NAMESPACE :

 importFrom(magrittr,"%>%") 

I suggest reading Writing R Extensions . Your question is addressed in paragraphs 1.1.3 and 1.5.1.

+53
Jan 16 '15 at 8:11
source share

One additional solution is to use the roxygen package. It is implemented as part of the devtools package. Once devtools installed, calling devtools::document() update your NAMESPACE for you. It also automatically creates .Rd files with documentation, which is convenient.

All you do is add a special comment in the format #' @import packagename to the file to import all functions from this package or #' @importFrom packagename functionname to import the function. You can have as many comments as you want in your files, so you can have a set of them at the top of each file or with each of your functions that require an external function.

Then you run devtools::document() and it will analyze your code looking for these comments and then create the appropriate NAMESPACE file for you. Easily.

+17
Jan 20 '16 at 15:32
source share

Assuming you are using the RStudio package, Hadley devtools and are listed by magrittr in the Importing a DESCRIPTION file section, here are the steps I took to make %>% work in my package (s) function.

First write down the function foo.R :

 #' Convert \code{data.frame} to \code{list}. #' #' @importFrom magrittr %>% #' @name %>% #' @rdname pipe #' @export #' @param x A \code{data.frame} object. #' @examples #' my_result <- foo(iris) #' foo <- function(x) { x %>% as.list() } 

Secondly, run devtools::document() .

Third, run devtools::load_all() .

This file will be created in your R/ directory, and your function should work as expected.

+6
Jan 21 '16 at 17:21
source share



All Articles