我在R中的pryr包中使用address()函数,并想知道是否期望以下结果…
x <- 1:10
add <- function(obj){address(obj)}
address(x)
# [1] "0x112d007b0"
add(x)
# [1] "0x11505c580"
即0x112d007b0!= 0x11505c580
我希望它们将是相同的值…有没有办法调整上面的函数添加以确保它获得相同的值?即获取父环境中的地址?
最佳答案 pryr ::: address定义为function(x)address2(check_name(substitute(x)),parent.frame()).如果你将pryr :::地址包装在另一个函数中,它的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"