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

1

6

@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 ?

Grownup answered 14/12, 2018 at 13:23 Comment(1)
"But the problem is that now the <<- operator is redefined and this doesn't work anymore" Nice, kill two birds with one stoneIgnition
G
2

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"
Grownup answered 14/12, 2018 at 13:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.