简体   繁体   English

magrittr包中的管道不适用于功能负载()

[英]Pipe in magrittr package is not working for function load()

It seem %>% in the magrittr package is not working for the function load() . 似乎magrittr包中的%>%不适用于函数load() This is my minimal example to reproduce my question. 这是我重现我的问题的最小例子。

## 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)

I don't understand why the pipe is not working for load() . 我不明白为什么管道不适用于load() Thanks for any suggestions. 谢谢你的任何建议。

The envir argument in load() needs to be specified as either globalenv() or parent.frame(3) . load()envir参数需要指定为parent.frame(3) 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"

The following also works: 以下也有效:

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

I'll try to explain why. 我会试着解释原因。 When you call load() from any environment, the function loads the new objects in the parent environment. 从任何环境调用load() ,该函数会在父环境中加载新对象。

Now, the global environment globalenv() is your R workspace. 现在,全局环境globalenv()是您的R工作区。 So, if you call load from the global environment (ie the workspace) everything works as you expect. 因此,如果从全局环境(即工作空间)调用load,一切都按预期工作。 Visualise this: 想象一下:

  • Global environment 全球环境
    • load()

However, if you call load() from inside a function, then you've inserted an environment in between load and the global environment. 但是,如果从函数内部调用load() ,则在load和全局环境之间插入一个环境。 Visualise this: 想象一下:

  • Global environment 全球环境
    • function 功能
      • load()

This is exactly what happens when you put %>% into the mix: 这正是将%>%放入混合时会发生的情况:

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

There are two solutions for resolving this. 有两种解决方案可以解决这个问题。 Either explicitly point to globalenv() or walk 3 steps up the chain to the global environment using parent.frame(3) . 要么明确指向globalenv()要么使用parent.frame(3)将链向上走3步到全局环境。


Note: There was an issue reported on GitHub for this. 注意: GitHub上报告了一个问题 Not sure what the resolution was, or if there is one yet. 不确定分辨率是什么,或者是否还有分辨率。 The issue was just reported in September. 这个问题刚刚在九月报道。

Many thanks to @Andrie for improving this explanation. 非常感谢@Andrie改进了这个解释。

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

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