Home > Net >  assign function does not work when piping to second argument
assign function does not work when piping to second argument

Time:11-22

I'm trying to assign a value to a variable using pipes. However, I get the following error.

> 1 %>% assign("a", .)
> a
Error: object 'a' not found

The following does not work either

> "a2" %>% assign(., 1)
> a2
Error: object 'a2' not found

Writing to stdout does not work either

> write(1, stdout()) %>% assign("a3", .)
1
> a3
Error: object 'a3' not found

How do I fix this? Thank you.

CodePudding user response:

Specify the environment to assign into when using a magrittr pipe:

library(magrittr)
if (exists("a")) rm(a)
1 %>% assign("a", ., .GlobalEnv)
a
## [1] 1

or use the magrittr eager pipe

if (exists("a3")) rm(a3)
1 %!>% assign("a", .)
a
## [1] 1

Alternately use the native R pipe.

if (exists("a")) rm(a)
1 |> assign("a", value = _)
a
## [1] 1

With stdout() it must be captured first:

if (exists("a3")) rm(a3)
write(1, stdout()) %>% capture.output %>% assign("a3", ., .GlobalEnv)
a3
## [1] 1

if (exists("a3")) rm(a3)
write(1, stdout()) %>% capture.output %!>% assign("a3", .)
a3
## [1] 1

if (exists("a3")) rm(a3)
write(1, stdout()) |> capture.output() |> assign("a3", value = _)
a3
## [1] 1
 
  • Related