我想写一个自定义管道操作符的地方,用的是operator name is open.它可以是例如%>%
、%|%
、:=
、...也许它需要根据需要的operator precedence来 Select ,就像在Same function but using for it the name %>% causes a different result compared when using the name :=中解释的那样.
使用的placeholder name is open但.
或_
是常见的,它需要是placed explicitly(不会自动放置作为第一个参数).
evaluation environment is open号.但在this answer中,似乎应该避免使用用户环境.
如果它与占位符具有相同的名称,它应该能够为keep the value in the user environment.
1 %>% identity(.)
#[1] 1
.
#Error: object '.' not found
. <- 2
1 %>% identity(.)
#[1] 1
.
#[1] 2
它应该能够update values in the user environment包括占位符的名称.
1 %>% assign("x", .)
x
#[1] 1
"x" %>% assign(., 2)
x
#[1] 2
1 %>% assign(".", .)
.
#[1] 1
"." %>% assign(., 2)
.
#[1] 2
x <- 1 %>% {names(.) <- "foo"; .}
x
#foo
# 1
应该是evaluate from left to right.
1 %>% . + 2 %>% . * 3
#[1] 9
目前,我有:
`:=` <- function(lhs, rhs) {
e <- exists(".", parent.frame(), inherits = FALSE)
. <- get0(".", envir = parent.frame(), inherits = FALSE)
assign(".", lhs, envir=parent.frame())
on.exit(if(identical(lhs, get0(".", envir = parent.frame(), inherits = FALSE))) {
if(e) {
assign(".", ., envir=parent.frame())
} else {
if(exists(".", parent.frame())) rm(., envir = parent.frame())
}
})
eval(substitute(rhs), parent.frame())
}
但它在try 时失败了:
. <- 0
1 := assign(".", .)
.
#[1] 0
下面给出了预期的结果,但我不确定它是否真的从左到右计算.
1 := . + 2 := . * 3
#[1] 9