本文介绍了包中的全局变量 - 更推荐哪种方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道全局变量通常是邪恶的,我应该避免它们,但如果我的包确实需要一个全局变量,这两种方法中哪一种更好?还有其他推荐的方法吗?

I do understand that generally global variables are evil and I should avoid them, but if my package does need to have a global variable, which of these two approaches are better? And are there any other recommended approaches?

  1. 使用对包可见的环境

  1. Using an environment visible to the package

pkgEnv <- new.env()
pkgEnv$sessionId <- "xyz123"

  • 使用选项

    options("pkgEnv.sessionId" = "xyz123")
    

  • 我知道还有一些其他线程询问如何实现全局变量,但我没有看到关于推荐哪个的讨论

    I know there are some other threads that ask about how to achieve global variables, but I haven't seen a discussion on which one is recommended

    推荐答案

    一些包使用隐藏变量(以 . 开头的变量),例如 .Random.seed.Last.value 在基础 R 中做.在你的包中你可以做

    Some packages use hidden variables (variables that begin with a .), like .Random.seed and .Last.value do in base R. In your package you could do

    e <- new.env()
    assign(".sessionId", "xyz123", envir = e)
    ls(e)
    # character(0)
    ls(e, all = TRUE)
    # [1] ".sessionId"
    

    但是在你的包中你不需要指定e.您可以使用 .onLoad() 挂钩在加载包时分配变量.

    But in your package you don't need to assign e. You can use a .onLoad() hook to assign the variable upon loading the package.

    .onLoad <- function(libname, pkgname) {
        assign(".sessionId", "xyz123", envir = parent.env(environment()))
    }
    

    请参阅 this question 及其答案,了解有关包变量的一些很好的解释.

    See this question and its answers for some good explanation on package variables.

    这篇关于包中的全局变量 - 更推荐哪种方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-24 06:21