为 `x < y <- z` 定义时 `<<-` 的歧义

ambiguity of `<<-` when defining it for `x < y <- z`

@g-grothendieck 对 的回答启发了我使用一些赋值函数,例如 ==<-><-.

查看以下内容:

`><-` <- function(e1,e2,value) replace(e1, e1 > e2, value)
x <- c(5,15)
x > 10 <- 42
x
# [1]  5 42

我也可以为<定义它:

`<<-` <- function(e1, e2, value) replace(e1, e1 < e2, value)
x <- c(5,15)
x < 10 <- 42
x
# [1] 42 15

但问题是现在 <<- 运算符被重新定义了,这不再起作用了:

x <<- "hello"

Error in replace(e1, which(e1 < e2), value) : argument "value" is missing, with no default

有趣的是 x < y <- z 调用 <<- 即使它没有被覆盖。

rm(`<<-`)
x < 10 <- 42

Error in x < 10 <- 42 : incorrect number of arguments to "<<-"

是否有办法在定义此自定义行为的同时保留 <<- 的原始行为?

这似乎有效:

`<<-` <- function(e1, e2, value){
  if(missing(value)) 
    eval.parent(substitute(.Primitive("<<-")(e1, e2)))
  else 
    replace(e1, e1 < e2,value)
}

x <- c(5,15)
x < 10 <- 42
x
# [1] 42 15

x <<- "hello"
x
# [1] "hello"