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

查看:22
本文介绍了从 [包] 导入 [功能] 在 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 在 base 中不存在",也会发生这种情况.

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 包,它会强制您为所有不明确的函数调用显式识别包:https://www.tidyverse.org/articles/2018/06/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天全站免登陆