Use explicit namespace with infix operator

2020-05-06 13:47发布

问题:

The dplyr R package has the %>% operator, which is a custom infix operator. If one attaches the namespace with library(dplyr) one can use this operator. In library code the library(dplyr) at the top of the file has no effect because the environment after executing the source code is stored; loaded packages have no effect on that.

So in order to use this in my library, I have these options:

  1. Just use library(dplyr) at the beginning of each function.
  2. Do not use the infix operator and rather write the functions with out the “pipe” operator %>%.
  3. Try to use dplyr::%>%.

The last option is what I want to do, but I cannot seem to get the syntax right. I have tried

dplyr::%>%

and get parsing errors. Also

dplyr::`%>%`

does not work. And

`dplyr::%>%`

does not work either. I don't think that there is any other way to place the backticks. Is this something that is possible in R or do I just have to use option 1 or 2?

回答1:

Just import the pipe operator, by adding a line like

importFrom(magrittr, "%>%")

in your NAMESPACE file, or if you're using roxygen2, putting

#' @importFrom magrittr %>%

into one of your .R files to do the same thing.

You may or may not want to export it as well. Do export it with a line like

export("%>%")

in your NAMESPACE file or with roxygen2

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

if you want your users to use the pipe operator when they are using your package. Don't export it if you only need it to be available internally.



标签: r dplyr