如何在函数内使用ls()搜索环境? [英] How to search an environment using ls() inside a function?
本文介绍了如何在函数内使用ls()搜索环境?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想找到一组函数并保存它们,因为我想将它们发送到Rdata文件中的远程服务器上,并且我不想在服务器上安装新的软件包.
I want to find a set of functions and save them, because I want to send them to a remote server in an Rdata file, and I don't want to install a new package on the server.
尽管我在使用以下方法时遇到了错误,但欢迎使用更简单/更好的方法.
Although I am getting an error using the approach below, easier / better approaches are welcome.
MWE:
这是两个虚拟函数:
abcd.fun.1 <- function() return(1)
abcd.fun.2 <- function() return(2)
我可以识别虚拟功能:
ls()[grep('abcd', ls())]
但是当我将其包装在一个函数中时:
But when I wrap this in a function:
find.test <- function(x) {
return(ls()[grep(x, ls())])
}
find.test('abcd')
该函数返回character(0)
最终我想
save(find.test('abcd'), file = test.Rdata)
推荐答案
- 为什么不对
ls
使用pattern=
自变量? - 在函数内调用
ls
会列出存在于 功能范围,不是全局环境(这在?ls
中有解释).
- Why not use the
pattern=
argument tols
? - Calling
ls
inside a function lists the objects that exist within the function scope, not the global environment (this is explained in?ls
).
如果要通过函数列出全局环境中的对象,请指定envir=.GlobalEnv
.
If you want to list the objects in the global environment from a function, specify envir=.GlobalEnv
.
x <- 1:10
f <- function() ls()
g <- function() ls(envir=.GlobalEnv)
h <- function() ls(envir=.GlobalEnv, pattern="[fg]")
f()
# character(0)
g()
# [1] "f" "g" "h" "x"
h()
# [1] "f" "g"
这篇关于如何在函数内使用ls()搜索环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文