How to search an environment using ls() inside a function?

空扰寡人 提交于 2019-12-09 10:05:09

问题


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:

Here are two dummy functions:

abcd.fun.1    <- function() return(1)
abcd.fun.2    <- function() return(2)

I can identify the dummy functions:

ls()[grep('abcd', ls())]

But when I wrap this in a function:

 find.test <- function(x) {
     return(ls()[grep(x, ls())])
 }
 find.test('abcd')

The function returns character(0)

Ultimately I would like to

 save(find.test('abcd'), file = test.Rdata)

回答1:


  1. Why not use the pattern= argument to ls?
  2. Calling ls inside a function lists the objects that exist within the function scope, not the global environment (this is explained in ?ls).

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"



回答2:


You need to tell your function to list objects in an environment other than itself, e.g. the global environment. (And while you're at it, you can also specify the regex pattern as an argument to ls.):

find.test <- function(x, envir=.GlobalEnv) {
  ls(pattern=x, envir=envir) 
}

See ?ls for more info about ls() and ?environment for other options to specify the environment.



来源:https://stackoverflow.com/questions/8142941/how-to-search-an-environment-using-ls-inside-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!