R地址函数

h.l*_*l.m 5 r pryr

我正在Raddress()中使用pryr包中的函数,并且想知道是否可以预期以下结果...

x <- 1:10
add <- function(obj){address(obj)}
address(x)
# [1] "0x112d007b0"
add(x)
# [1] "0x11505c580"
Run Code Online (Sandbox Code Playgroud)

即 0x112d007b0 != 0x11505c580

我希望它们的值相同……有没有办法调整add上面的函数以确保它得到相同的值?即获取父环境中的地址?

ale*_*laz 3

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>  
Run Code Online (Sandbox Code Playgroud)

具体来说,除非我在某个地方丢失了它,否则它的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"
Run Code Online (Sandbox Code Playgroud)

我不确定如何“修复”这个问题(有时可能需要这样的行为),除了执行以下操作之外:

add = pryr::address
add(x)
#[1] "0x6fca100"
Run Code Online (Sandbox Code Playgroud)