简体   繁体   English

选择要从R包加载的函数

[英]Choose function to load from an R package

I like using function reshape from the matlab package, but I need then to specify base::sum(m) each time I want to sum the elements of my matrix or else matlab::sum is called, which only sums by columns.. 我喜欢从matlab包中使用函数reshape ,但每次我想对矩阵元素求和时,都需要指定base::sum(m) ,否则需要调用matlab::sum ,它仅按列求和。

I need loading package gtools to use the rdirichlet function, but then the function gtools::logit masks the function pracma::logit that I like better.. 我需要加载gtools包才能使用rdirichlet函数,但是函数gtools::logit掩盖我更喜欢的函数pracma::logit

I gess there are no such things like: 我没有这样的事情:

library(loadOnly = "rdirichlet", from = "gtools")

or 要么

library(loadEverythingFrom = "matlab", except = "sum")

.. because functions from the package matlab may internaly work on the matlab::sum function. ..因为来自matlab包的函数可能会在内部作用于matlab::sum函数。 So the latter must be loaded. 因此, 必须加载后者。 But is there no way to get this behavior from the point of view of the user? 但是有没有办法从用户的角度来获得这种行为? Something that would feel like: 感觉像是:

library(pracma)
library(matlab)
library(gtools)
sum <- base::sum
logit <- pracma::logit

.. but that would not spoil your ls() with all these small utilitary functions? ..但这不会破坏所有这些小的实用功能的ls()吗?

Maybe I need defining my own default namespace? 也许我需要定义自己的默认名称空间?

To avoid spoiling your ls , you can do something like this: 为了避免破坏ls ,您可以执行以下操作:

.ns <- new.env()
.ns$sum <- base::sum
.ns$logit <- pracma::logit
attach(.ns)

To my knowledge there is no easy answer to what you want to achieve. 据我所知,要达到的目标没有简单的答案。 The only dirty hack I can think of is to download the source of the packages "matlab", "gtools", "pracma" and delete the offending functions from their NAMESPACE file prior to installation from source (with R CMD INSTALL package). 我唯一能想到的肮脏技巧是在从源代码安装(带有R CMD INSTALL软件包)之前,下载软件包“ matlab”,“ gtools”,“ pracma”的源代码,并从其NAMESPACE文件中删除有问题的功能。

However, I would recommend using the explicit notation pracma::logit, because it improves readability of your code for other people and yourself in the future. 但是,我建议使用显式表示法pracma :: logit,因为它可以提高代码对其他人和您自己的可读性。

This site gives a good overview about package namespaces: http://r-pkgs.had.co.nz/namespace.html 该站点很好地概述了程序包名称空间: http : //r-pkgs.had.co.nz/namespace.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM