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

最后都变了- 提交于 2019-12-06 00:53:21

问题


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


来源:https://stackoverflow.com/questions/53780628/ambiguity-of-when-defining-it-for-x-y-z

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!