与infix运算符一起使用显式命名空间 [英] Use explicit namespace with infix operator

查看:83
本文介绍了与infix运算符一起使用显式命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

dplyr R程序包具有%>%运算符,它是一个自定义的中缀运算符。如果将名称空间附加到 library(dplyr),则可以使用此运算符。在库代码中,文件顶部的 library(dplyr)没有任何作用,因为存储了执行源代码后的环境。加载的软件包对此没有影响。

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. 在每个函数的开头仅使用 library(dplyr)

  2. 请勿使用infix运算符,而不用 pipe运算符%>%编写函数。

  3. 尝试使用 dplyr ::%>%

  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::%>%

并获得解析错误。另外

dplyr::`%>%`

不起作用。并且

`dplyr::%>%`

也不起作用。我认为没有其他方法可以放置反引号。这在R中是可能的,还是我只需要使用选项1或2?

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?

推荐答案

只需导入管道运算符,通过添加

Just import the pipe operator, by adding a line like

importFrom(magrittr, "%>%")

在您的 NAMESPACE 文件中,或者如果您使用的是 roxygen2 ,放在

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

#' @importFrom magrittr %>%

放入您的 .R 文件之一即可执行同样的操作。

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("%>%")

在您的 NAMESPACE 文件中或使用 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.

这篇关于与infix运算符一起使用显式命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆