R地址功能

时间:2015-10-22 18:06:31

标签: r pryr

我正在使用R中address()包中的pryr函数,并想知道是否会出现以下结果......

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

即。 0x112d007b0!= 0x11505c580

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

1 个答案:

答案 0 :(得分:2)

pryr:::address定义为function(x) address2(check_name(substitute(x)), parent.frame())。如果您将pryr:::address包裹在另一个函数中,则其parent.frame()会发生变化。 E.g:

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"