繁体   English   中英

R中如何获取调用函数环境中的对象?

[英]How to obtain objects in the environment of the calling function in R?

test <- function(){    
a = 3
b = c(1,2,3)
c = matrix(-99, 3, 4)
print(getObjects())
}

getObjects <- function(){
return(ls(pos=1))
}

我希望函数测试只打印出 a、b、c,因为这些是函数 test() 范围内的唯一对象(它可以打印测试访问的其他对象/函数,例如 getObjects() 在这种情况下)。 但是没有选择 pos 给了我那个? 有没有办法在“调用”函数(此处为测试)中获取对象,以便我可以对其进行一些操作,并且“被调用”函数(此处为 getObjects)可以返回结果。 我的函数 getObjects 应该对通过执行 ls() 获得的对象进行操作。

test <- function(){    
  a = 3
  b = c(1,2,3)
  c = matrix(-99, 3, 4)
  print(getObjects())
}

getObjects <- function(){
  return(ls(envir=parent.frame(n = 1)))
}

test()
#[1] "a" "b" "c"

当然,您可以简单地使用ls的默认值:

test <- function(){    
  a = 3
  b = c(1,2,3)
  c = matrix(-99, 3, 4)
  ls()
}

从文档:

名称:列出可用对象时使用的环境。 默认为当前环境。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM