从[包]导入R中的[功能] [英] From [package] import [function] in R

查看:102
本文介绍了从[包]导入R中的[功能]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python或R处理数据时,我们通常会加载多个程序包.在某些情况下,两个软件包(例如foobar)可能每个都包含某些功能(例如do_stuff).

Working with data in Python or R, we often load several packages. In some cases, two packages (e.g. foo and bar) might each contain some function (e.g. do_stuff).

在Python中对此进行管理以防止歧义或意外的方式如下:

The way this is managed in Python to prevent ambiguity or surprises is like:

from foo import do_stuff
from bar import other_function    # (does not load/import do_stuff() from bar)

在R中,我看到的所有代码都只导入带有 多个library(package_name)语句.我认为这将导致很难捕获的错误.例如,请参见重新排序因数会得出不同的结果,取决于要加载的软件包.实际上,即使没有屏蔽,因为reorder.factor不存在于基数中",也会发生这种情况.

In R, all the code I see just imports whole packages with multiple library(package_name) statements. I would think this would lead to very difficult-to-catch bugs. For example, see Reordering factor gives different results, depending on which packages are loaded. In fact this occurred even though "there is no masking, since reorder.factor doesn't exist in base."

我希望这个问题的一般答案类似于上面的from package import function代码,但事实并非如此.实际上,被接受的(且唯一的)答案仅说明了问题存在的原因(而不是低估该贡献).在答案的注释中提供了一种解决方法,但是该解决方法特定于该特定功能(reorder).

I expected the general answer to this problem to be something like the from package import function code above, but it wasn't. In fact the accepted (and only) answer just explains why the problem exists (not to downplay that contribution). There's a workaround provided in a comment of the answer, but that workaround is specific to that particular function (reorder).

是否可以通过一般方式仅从R中的特定程序包中导入特定功能?这样一来,我就可以对代码中所有函数调用的来源都保持谨慎和明确的态度,并确保它们按我认为的方式工作?

Is there a general way that I can import only a specific function from a specific package in R? So that I can be deliberate and unambiguous about where all of the function calls in my code come from and ensure that they do what I think they're doing?

推荐答案

您可以使用package::function()构造显式告诉R应该将哪个包用于给定的函数.您甚至可以使用它从尚未加载library的程序包中调用函数.

You can explicitly tell R which package should be used for a given function using the package::function() construction. You can even use that to call functions from packages that you haven't loaded with library.

library(dplyr) # Has a function called filter()
library(plyr) # Also has a filter() function

dplyr::filter(foo)
plyr::filter(bar)

如果要确保最大程度地减少代码混乱的可能性,我强烈建议使用conflicted软件包,该软件包将强制您为所有歧义函数调用明确标识该软件包:

If you want to make sure you're minimizing the possibility for confusion in your code, I highly recommend the conflicted package, which forces you to explicitly identify the package for all ambiguous function calls: https://www.tidyverse.org/articles/2018/06/conflicted/

这篇关于从[包]导入R中的[功能]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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