定义 `(<-` 运算符时获取 x 的名称 [英] Get name of x when defining `(<-` operator

查看:16
本文介绍了定义 `(<-` 运算符时获取 x 的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义 (<- 并访问左侧参数的名称:

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) := 如果使用 := 没问题,那么:

2) := If using := is ok then:

`:=` <- 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

这篇关于定义 `(&lt;-` 运算符时获取 x 的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆