I am trying to write a simple function in in r
that will search the .GlobalEnv
for objects with a specific pattern in their names, then take that list and bind the elements into a data frame.
When run separately, this works as expected:
# create sample data
df1_pattern_to_find <- data.frame(a = 1, b = 2)
df2_pattern_to_find <- data.frame(a = 3, b = 4)
# use mget to generate a list of objects
list_of_objects <- mget(ls(pattern="_pattern_to_find"))
# bind the elements together into a data frame
do.call("rbind", list_of_objects)
a b
df1_pattern_to_find 1 2
df2_pattern_to_find 3 4
However, when I wrap the above in a function it returns NULL
:
gather_function <- function() {
list_of_objects <- mget(ls(pattern="_pattern_to_find"))
df <- do.call("rbind", list_of_objects)
df
}
gather_function()
NULL
I have tried explicitly setting envir
within mget
to .GlobalEnv
and that doesn't seem to be the issue.
I know I am missing something simple here.
mget() function in R programming works similar to get() function but, it is able to search for multiple data objects rather than a single object in get() function.
That is with() function enables us to evaluate an R expression within the function to be passed as an argument. It works on data frames only. That is why the outcome of the evaluation of the R expression is done with respect to the data frame passed to it as an argument.
As you're calling ls
and mget
within a function, the environment is no longer the same as when called from the top-level environment.
You can hard-code the environment to search the top-level as follows:
list_of_objects <- mget(ls(.GlobalEnv, pattern = "_pattern_to_find"), envir = .GlobalEnv)
Your problem was ls
wasn't returning any objects in the first place so setting the envir
parameter within mget
alone won't help.
An alternative which avoids hard-coding .GlobalEnv
is to search all enclosing parent frames:
mget(apropos("_pattern_to_find"), inherits = TRUE)
This will match the pattern "_pattern_to_find"
and return any objects in enclosing environments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With