overdisperse
overdisperse

Reputation: 426

Is there a "correct" way of using piping with load()?

It seems the pipe operator creates a temporary environment that then discards the loaded data:

library(magrittr)
"thing.rdata" -> thing
# Nothing happens:
thing %>% load
# Works as expected:
thing %>% load(envir=globalenv())

I'm not sure if using globalenv() is the best way to solve this issue as I was hoping to keep something simple like load(thing) (which does work).

Upvotes: 1

Views: 71

Answers (1)

overdisperse
overdisperse

Reputation: 426

A kind reddit user provided me a link that had the answer.

I'll quote the relevant section:

The use of assign with the pipe does not work because it assigns it to a temporary environment used by %>%. If you do want to use assign with the pipe, you must be explicit about the environment:

env <- environment()
"x" %>% assign(100, envir = env)

[...]

Other functions with this problem include get() and load().

Source: http://r4ds.had.co.nz/pipes.html

Upvotes: 1

Related Questions