定义`(< -`运算符时,获取x的名称 [英] Get name of x when defining `(<-` operator
问题描述
我想定义(<-
并访问左侧参数的名称:
I want to define (<-
and access the name of the left hand side argument :
*<-
函数在内部使用中间的'*tmp*'
变量.是否仍有可能获得x的名称?
*<-
functions use internally an intermediate '*tmp*'
variable. Is it still possible to get the name of x ?
`(<-` <- function(x,value){
print(deparse(substitute(value)))
print(deparse(substitute(x)))
print(match.call())
value
}
foo <- 0
(foo) <- 3
# [1] "3"
# [1] "*tmp*"
# `(<-`(x = `*tmp*`, value = 3)# [1] "3"
我想从函数内部获取"foo".
I want to get "foo" from inside the function.
我试图通过使用tracemem
来破解它,即在函数内部调用sapply(ls(envir = parent.frame()),tracemem)
和tracemem(x)
,但是foo
,*temp*
和x
的地址都不同.
I tried to hack it by using tracemem
, i.e. calling sapply(ls(envir = parent.frame()),tracemem)
and tracemem(x)
inside of the functions but the address of foo
, *temp*
and x
are all different.
推荐答案
1)如果您愿意更改它以使呼叫为:
1) If you are willing to change it so that the call is:
fooify[foo] <- 99
然后我们可以这样做,其中foo
不需要事先存在:
then we can do it like this where foo
need not exist beforehand:
fooify <- structure(NA, class = "fooify")
"[<-.fooify" <- function(x, var, value) {
print(deparse(substitute(var)))
eval.parent(substitute(var <- value))
x
}
# test
if (exists("foo")) rm(foo)
fooify[foo] <- 99
## [1] "foo" <-- this comes from the print statement
foo
## [1] 99
2):= 如果可以使用:=
,则:
`:=` <- function(lhs, rhs) {
print(deparse(substitute(lhs)))
eval.parent(substitute(lhs <- rhs))
}
# test
if (exists("foo")) rm(foo)
foo := 99
## [1] foo <-- this comes from print statement
foo
## [1] 99
这篇关于定义`(< -`运算符时,获取x的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!