Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using mget within a function in R

Tags:

r

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.

like image 470
BillPetti Avatar asked Mar 09 '18 14:03

BillPetti


People also ask

What does Mget do in R?

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.

How would you use the with function in R?

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.


Video Answer


1 Answers

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.

like image 145
ruaridhw Avatar answered Sep 20 '22 09:09

ruaridhw