我正在使用Raddress()
中的包中的函数pryr
,并且想知道是否可以预期以下结果...
x <- 1:10
add <- function(obj){address(obj)}
address(x)
# [1] "0x112d007b0"
add(x)
# [1] "0x11505c580"
即0x112d007b0!= 0x11505c580
我希望它们的值相同……有没有办法调整add
上面的函数以确保它得到相同的值?即在父环境中获取地址?
pryr:::address
定义为function(x) address2(check_name(substitute(x)), parent.frame())
。如果你包装pryr:::address
在另一个函数中,它的parent.frame()
变化。例如:
myfun = function() parent.frame()
myfunwrap = function() { print(environment()); myfun() }
myfun()
#<environment: R_GlobalEnv>
myfunwrap()
#<environment: 0x063725b4>
#<environment: 0x063725b4>
myfunwrap()
#<environment: 0x06367270>
#<environment: 0x06367270>
具体来说,除非我在某个地方丢失了它,否则它pryr::address
的工作方式似乎如下:
ff = inline::cfunction(sig = c(x = "vector", env = "environment"), body = '
Rprintf("%p\\n", findVar(install("x"), env));
return(eval(findVar(install("x"), env), env)); //pryr::address does not evaluate
') #this is not a general function; works only for variables named "x"
assign("x", "x from GlobalEnv", envir = .GlobalEnv)
ff1 = function(x) ff(x, parent.frame())
ff2 = function(x) ff1(x)
pryr::address(x)
#[1] "0x6fca100"
ff(x, .GlobalEnv)
#0x06fca100
#[1] "x from GlobalEnv"
ff1(x)
#0x06fca100
#[1] "x from GlobalEnv"
ff1(x)
#0x06fca100
#[1] "x from GlobalEnv"
ff2(x)
#0x06375340
#[1] "x from GlobalEnv"
ff2(x)
#0x0637480c
#[1] "x from GlobalEnv"
除了执行以下操作之外,我不确定如何“修复”它(有时可能希望表现得像这样):
add = pryr::address
add(x)
#[1] "0x6fca100"