简体   繁体   English

当管道传输到第二个参数时,分配 function 不起作用

[英]assign function does not work when piping to second argument

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.谢谢你。

Specify the environment to assign into when using a magrittr pipe:指定使用 magrittr pipe 时分配到的环境:

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

or use the magrittr eager pipe或者使用 magrittr eager pipe

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

Alternately use the native R pipe.交替使用本机 R pipe。

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

With stdout() it must be captured first:使用stdout()必须首先捕获它:

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
 

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

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