访问函数中的多个匹配对象而不在函数调用中显式声明名称

Accessing multiple matched objects in a function without explicitly stating the names in the function call

我想开发一个简单的功能,使我能够保存特定特征的图表。例如,我正在 运行 进行一些分析,生成一组直方图:

# Data  and Libs
data(mtcars); require(ggplot2)

# Graphs

## A
grph_a <- ggplot(data = mtcars) +
  geom_histogram(aes(mpg)) +
  ggtitle("MPG")

## B
grph_b <- ggplot(data = mtcars) +
  geom_histogram(aes(cyl)) +
  ggtitle("CYL")

我不想为每个图表编写 ggsave 命令,而是想通过函数来​​完成。这是有道理的,因为我将在各种类似项目中对许多图表重复相同的步骤。我想让函数做一件事:

理想情况下,我希望函数调用看起来像那样

ExportGraphs(graphNamePhrase = "grph_", filesPath = "Somewhere/GaphsAndStuff/)

我不想指定更多内容。

函数

我的函数看起来像这样:

ExportGraphs <- function(graphNamePhrase = "grph_",
                         filesPath, objects = ls()) {

  # Check if required packages are available
  req_pkgs <- c("ggplot2","grid")
  ## Check if the package is loaded and load if needed
  for (i in 1:length(req_pkgs)) {
    pkg <- req_pkgs[i]
    if (length(grep(pkg, search())) == 0) {
      lapply(pkg, require, character.only = TRUE)
    }
  }

  # Create list of objects
  save_grphs <- grep(pattern = graphNamePhrase, x = objects,
                     ignore.case = TRUE, value = TRUE)

  # Create save loop
  for (i in 1:length(save_grphs)) {

    # Create file path
    fle_path <- paste0(filesPath, save_grphs[i], ".png")

    # Save file
    ggsave(filename = fle_path, plot = save_grphs[i],
           width = 7, height = 7, units = 'cm', scale = 2, dpi = 600)
  }

}

问题

很明显,代码:

  save_grphs <- grep(pattern = graphNamePhrase, x = objects,
                     ignore.case = TRUE, value = TRUE)

将不起作用,因为通过 objects = ls() 传递的是一个字符串。我的问题是我怎样才能绕过它。有没有办法在调用函数的父框架上使用 get ?这不是最简单的解决方案,但我可以通过字符串搜索对象。或者我可以 运行 ls 在函数调用中使用 grep 并传递所有匹配的对象吗?


评论跟进

mget

我尝试了 mget 的解决方案:

ExportGraphs <- function(graphNamePhrase = "grph_",
                         filesPath, objects = ls()) {

  # Check if required packages are available
  req_pkgs <- c("ggplot2","grid")
  ## Check if the package is loaded and load if needed
  for (i in 1:length(req_pkgs)) {
    pkg <- req_pkgs[i]
    if (length(grep(pkg, search())) == 0) {
      lapply(pkg, require, character.only = TRUE)
    }
  }

  # Create list of objects
  save_grphs <- grep(pattern = graphNamePhrase, x = objects,
                     ignore.case = TRUE, value = TRUE)
  save_grphs <- mget(objects[save_grphs])

  # Create save loop
  for (i in 1:length(save_grphs)) {

    # Create file path
    fle_path <- paste0(filesPath, save_grphs[i], ".png")

    # Save file
    ggsave(filename = fle_path, plot = save_grphs[[i]],
           width = 7, height = 7, units = 'cm', scale = 2, dpi = 600)
  }

}

但似乎我必须调整循环,因为订阅似乎越界了:

Error in save_grphs[[i]] : subscript out of bounds
Called from: inherits(plot, "ggplot")

这对我有用。还有很多地方可以进一步优化功能:

ExportGraphs <- function(graphNamePhrase = "grph_",
                         filesPath, objects = ls()) {

  # Check if required packages are available
  req_pkgs <- c("ggplot2","grid")
  ## Check if the package is loaded and load if needed
  for (i in 1:length(req_pkgs)) {
    pkg <- req_pkgs[i]
    if (length(grep(pkg, search())) == 0) {
      lapply(pkg, require, character.only = TRUE)
    }
  }

  # Create list of objects
  index <- grep(pattern = graphNamePhrase, x = objects,
                     ignore.case = TRUE)
  save_grphs <- mget(objects[index])
  # Create save loop
  for (i in 1:length(save_grphs)) {

    # Create file path
    fle_path <- paste0(filesPath, objects[index][i], ".png")

    # Save file
    ggsave(filename = fle_path, plot = save_grphs[[i]],
           width = 7, height = 7, units = 'cm', scale = 2, dpi = 600)
  }

}

尝试这样的事情:

ExportGraphs <- function(graphNamePhrase = "grph_", 
                         filesPath = "Somewhere/GaphsAndStuff",
                         object = ls()) {
  lapply(object[substr(names(object), 1, nchar(graphNamePhrase)) == graphNamePhrase], 
         function(plot.list.el){
           ggsave(plot.list.el, filename = paste(filesPath, paste0(names(plot.list.el), 
                                                                   ".pdf"),
                                                 sep = "/"))
         })
}


# testing the function
dat <- data.frame(x = rnorm(100))
object <- list(grph_asd = ggplot(dat, aes(x = x)) + geom_histogram(),
               grp_noplot = ggplot(dat, aes(x)) + geom_histogram())

# save the first, but not the second plot to the working directory

ExportGraphs(filesPath = "~", object = object)