R 中的全局变量

发布于 2024-07-29 19:08:21 字数 38 浏览 2 评论 0原文

我正在查阅手册,我想问社区: 我们如何在函数内设置全局变量?

I am poking into the manuals, I wanted to ask the community:
How can we set global variables inside a function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

稍尽春風 2024-08-05 19:08:21

正如 Christian 对 assign() 的回答所示,有一种在全局环境中进行分配的方法。 一种更简单、更短(但不是更好......坚持分配)的方法是使用 <<- 运算符,即

    a <<- "new" 

在函数内部。

As Christian's answer with assign() shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<- operator, ie

    a <<- "new" 

inside the function.

你穿错了嫁妆 2024-08-05 19:08:21

我找到了如何在 邮件列表发帖中设置全局变量的解决方案通过分配

a <- "old"
test <- function () {
   assign("a", "new", envir = .GlobalEnv)
}
test()
a  # display the new value

I found a solution for how to set a global variable in a mailinglist posting via assign:

a <- "old"
test <- function () {
   assign("a", "new", envir = .GlobalEnv)
}
test()
a  # display the new value
記憶穿過時間隧道 2024-08-05 19:08:21

.GlobalEnv$a <- "new" 怎么样? 我在这里看到了在特定环境中创建变量的显式方法: http://adv- r.had.co.nz/Environments.html。 它似乎比使用 assign() 函数更短。

What about .GlobalEnv$a <- "new" ? I saw this explicit way of creating a variable in a certain environment here: http://adv-r.had.co.nz/Environments.html. It seems shorter than using the assign() function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文