R writing style - require vs. ::

后端 未结 2 1988
没有蜡笔的小新
没有蜡笔的小新 2020-12-31 01:40

OK, we\'re all familiar with double colon operator in R. Whenever I\'m about to write some function, I use require(), but I was always thinking a

相关标签:
2条回答
  • 2020-12-31 02:25

    "Why should one prefer require over :: when writing a function?"

    I usually prefer require due to the nice TRUE/FALSE return value that lets me deal with the possibility of the package not being available up front before getting into the code. Crash as early as possible instead of halfway through your analysis.

    I only use :: when I need to make sure I am using the correct version of a function, not a version from some other package that is masking the name.

    On the other hand, :: operator gets the variable from the package, while require loads whole package (at least I hope so), so speed differences came first to my mind. :: must be faster than require.

    I think you may be ignoring the effects of lazy loading which is used by the foreign package according to the first page of its manual. Essentially, packages that use lazy loading defer the loading of objects, such as functions, until the objects are called upon for the first time. So your argument that ":: must be faster than require" is not necessarily true as foreign is not loading all of its contents into memory when you attach it with require. For full details on lazy loading, see Prof. Ripley's article in RNews, Volume 4, Issue 2.

    0 讨论(0)
  • 2020-12-31 02:26

    Since the time to load a package is almost always small compared to the time you spend trying to figure out what the code you wrote six months ago was about, in this case coding for clarity is the most important thing.

    For scripts, having a call to require or library at the start lets you know which packages you need straight away.

    Similarly, calling require (or a wrapper like requirePackage in Hmisc or try_require in ggplot2) at the start of a function is the most unambiguous way of showing that you need to use that package.

    :: should be reserved for cases when you have naming conflicts between packages – compare, e.g.,

    Hmisc::is.discrete
    

    and

    plyr::is.discrete
    
    0 讨论(0)
提交回复
热议问题