find_object | R Documentation |
Find the environment where an object exists
find_object(
value = NULL,
name = NULL,
mode = "any",
from = parent.frame(),
until = emptyenv(),
which = c("first", "last", "all")
)
value |
The R object whose location should be identified. |
name |
The name of the object to locate. |
mode |
The |
from |
An |
until |
An |
which |
If |
A named list with elements name
and envir
, where name
is the
name of the located object in environment envir
.
If no object could be located, then NULL is returned.
If more than one matching object could be located, then a list of
all matching (name, environment) lists is returned if which = "all"
.
If which = "first"
, then the first match is returned,
and if which = "last"
, then the last match is returned.
A matching object is looked for in environment from
. If it is found
there, then from
is returned. If not found there, the parent
environment of from
is searched, and so on, until an environment in
until
, or the "empty" environment
(emptyenv()
) is reached. In such cases,
no matching object could be found and NULL is returned.
find_object()
with arguments value
locates an object of any name
with value value
in one of the environments searched.
find_object()
with arguments name
and mode
locates an object
with name name
and mode mode
in one of the environments searched.
This is how base::exists()
, base::get()
, and base::assign()
locate
an object based on its name and mode.
For example, exists(name) == !is.null(find_object(name = name))
.
envir <- find_object(name = name) if (is.null(envir)) stop(sprintf("Object %s not found", sQuote(name))) object <- get(name, envir = envir, inherits = FALSE)
find_object(name = "pi")
find_object(name = "pi", mode = "character") ## non-existing
find_object(name = "rnorm", mode = "function")
f <- local({
a <- 42
pi <- 3.14
function() pi * a
})
env <- find_object(name = "a", from = f)$envir
utils::ls.str(env)
f <- local({
a <- 42
local({
pi <- 3.14
function() pi * a
})
})
env_a <- find_object(name = "a", from = f)$envir
utils::ls.str(env_a)
env_pi <- find_object(name = "pi", from = f)$envir
utils::ls.str(env_pi)
stopifnot(
identical(environment(f), env_pi),
identical(parent.env(env_pi), env_a)
)
find_object(value = rnorm)
my_sum <- rnorm
find_object(value = my_sum)
find_object(value = my_sum, from = parent_env())
my_sum <- local(sum)
find_object(value = my_sum)
my_find <- function(object, envir = parent.frame()) {
find_object(value = object, from = envir)
}
my_fcn <- local({
g <- sum ## this is never found
function(f = NULL) {
if (is.null(f)) {
f <- g ## this is found first
my_find(f)
} else {
my_find(f, envir = parent.frame()) # skip argument 'f'
}
}
})
my_fcn()
my_fcn(my_sum)
topenv()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.