在R中的函数中使用mget

时间:2021-06-24 22:49:58

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.

我试图在r中编写一个简单的函数,它将在.GlobalEnv中搜索名称中具有特定模式的对象,然后获取该列表并将元素绑定到数据框中。

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:

但是,当我在函数中包装上面时,它返回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.

我已经尝试在mget中明确地将envir设置为.GlobalEnv,这似乎不是问题。

I know I am missing something simple here.

我知道我在这里缺少一些简单的东西。

1 个解决方案

#1


2  

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.

当您在函数中调用ls和mget时,环境不再与从顶层环境调用时的环境相同。

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.

你的问题是ls没有返回任何对象,所以在单独的mget中设置envir参数无济于事。


An alternative which avoids hard-coding .GlobalEnv is to search all enclosing parent frames:

避免硬编码的替代方法.GlobalEnv是搜索所有封闭的父帧:

mget(apropos("_pattern_to_find"), inherits = TRUE)

This will match the pattern "_pattern_to_find" and return any objects in enclosing environments.

这将匹配模式“_pattern_to_find”并返回封闭环境中的任何对象。

#1


2  

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.

当您在函数中调用ls和mget时,环境不再与从顶层环境调用时的环境相同。

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.

你的问题是ls没有返回任何对象,所以在单独的mget中设置envir参数无济于事。


An alternative which avoids hard-coding .GlobalEnv is to search all enclosing parent frames:

避免硬编码的替代方法.GlobalEnv是搜索所有封闭的父帧:

mget(apropos("_pattern_to_find"), inherits = TRUE)

This will match the pattern "_pattern_to_find" and return any objects in enclosing environments.

这将匹配模式“_pattern_to_find”并返回封闭环境中的任何对象。