通过函数打印图

时间:2017-12-21 19:50:16

标签: r list ggplot2

我有一份清单,

item1 <- list(1:5)
item2 <- list(5:10)
item3 <- list(ggplot(mtcars, aes(x=as.factor(cyl) )) + geom_bar())

list <- list("item1"=item1, "item2"=item2, "item3.plt"=item3)

在这种情况下,其中一个列表项有&#34; .plt&#34;作为它的名字的一部分。 (其中包含ggplot图表)

我正在编写一个函数来将此列表作为参数,以便它将打印所有具有&#34; .plt&#34;的项目。部分为图形对象。

print.plots <- function(x){

e <- list2env(x) #do I need this?

list <- list()
  a <- deparse(substitute(x))
  for(i in 1:length(names(x))){
    if(grepl(".plt", names(x)[i])){
      list[i] <- list(paste0(paste0(a,"$"),names(x)[i]))
      # Print here?
    }

  }
  return(list)
}

print.plots(list)

我已经让return(list)查看输出是什么,它显示了3个项目的列表,前2个是NULL,第3个是我需要的图表的名称打印。

[[1]]
NULL
[[2]]
NULL
[[3]]
"list$item3.plt"

如果没有&#34; .plt&#34;我的if条件似乎不包含列表项在他们的名字中,情节本身没有被打印(即使我删除了return语句)。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

这样简单
list[grepl("\\.plt", names(list))]

应该从print.plots函数中获得与我想要的结果非常接近的结果。

至于写一个功能,一些建议。

  1. 避免使用单词list作为对象。在下面的示例中,我将mylist代替我们。

  2. print_plots使用下划线而非点。 print.plots可能会导致S3类出现问题。

  3. 在下面的示例中,我们查找项目结尾有.plt的任何项目,然后返回名称并打印图表。

    library(ggplot2)
    
    item1 <- list(1:5)
    item2 <- list(5:10)
    item3 <- list(ggplot(mtcars, aes(x=as.factor(cyl) )) + geom_bar())
    
    mylist <- list("item1"=item1, "item2"=item2, "item3.plt"=item3)
    
    print_plots <- function(x) { 
      plts <- grepl("\\.plt", names(x))
    
      if (any(plts)) {
        message(sprintf("Plots in %s are:", deparse(substitute(x)))) 
        lapply(which(plts), function(i) {y <- unlist(x[i], recursive = FALSE); print(y)}) 
      } else {
        message(sprintf("There are no plots in %s.", deparse(substitute(x)))) 
      }
      invisible(NULL)
    }
    
    print_plots(mylist)
    # Plots in mylist are:
    # $item3.plt