ambiguity of `<<-` when defining it for `x &

2020-07-10 08:47发布

问题:

@g-grothendieck's answer to this question inspired me to play with some assignment functions such as ==<- or ><-.

See the following :

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

I can also define it for < :

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

But the problem is that now the <<- operator is redefined and this doesn't work anymore :

x <<- "hello"

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

Interestingly x < y <- z calls <<- even when it's not been overwritten.

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

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

Would there be a way to keep the original behavior of <<- while still defining this custom behavior ?

回答1:

This seems to work :

`<<-` <- 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"