r语言 - magrittr 包中的管道对函数 load() 不起作用



似乎 magrittr 包中的%>%不适用于函数load() 。这是我重现我的问题的最小示例。

## Create two example variables and save to tempdir()
a <- 1
b <- 1
save(list = ls(), file = file.path(tempdir(), 'tmp.RData'))
## Remove all variables and load into global environment
# rm(list = ls())
load(file.path(tempdir(), 'tmp.RData'))
ls()
# [1] "a" "b"
# Write the same code with pipe "%>%", but not variable is loaded
# rm(list =ls())
library(magrittr)
tempdir() %>% file.path('tmp.RData') %>% load
ls()
# character(0)

我不明白为什么管道对load()不起作用.感谢您的任何建议。

load() 中的envir参数需要指定为 globalenv()parent.frame(3)

# in a fresh R session ...
a <- 1
b <- 1
save(list = ls(), file = file.path(tempdir(), 'tmp.RData'))
# in another fresh session ...
ls()
# character(0)
tempdir() %>% file.path("tmp.RData") %>% load(envir = globalenv())
ls()
# [1] "a" "b"

以下内容也有效:

tempdir() %>% file.path("tmp.RData") %>% load(envir = parent.frame(3))

我会试着解释为什么。 从任何环境调用load()时,该函数将加载父环境中的新对象。

现在,全局环境globalenv()是 R 工作区。 因此,如果您从全局环境(即工作区)调用负载,则一切都按预期工作。 可视化这一点:

  • 全球环境
    • load()

但是,如果从函数内部调用load(),则在加载和全局环境之间插入了一个环境。 可视化这一点:

  • 全球环境
    • 功能
      • load()

这正是当您将%>%放入混合中时发生的情况:

  • 全球环境
    • %>%
      • load()

有两种解决方案可以解决此问题。 要么明确指向globalenv(),要么使用 parent.frame(3) 沿着链条向上走 3 步到全球环境。


注意:GitHub 上报告了一个问题。 不确定解决方案是什么,或者是否有解决方案。 该问题刚刚在 9 月报告。

非常感谢@Andrie改进了这个解释。

最新更新