我有一份清单,
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)
在这种情况下,其中一个列表项将“.plt”作为其名称的一部分。 (其中包含ggplot图)
我正在编写一个函数来将此列表作为参数,以便它将打印所有具有“.plt”部分的项目作为图形对象。
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个项目的列表,前两个是NULL
,第三个有我需要打印的图表的名称。
[[1]]
NULL
[[2]]
NULL
[[3]]
"list$item3.plt"
我的if
条件似乎不包括名称中没有“.plt”的列表项,并且图表本身没有被打印(即使我删除了return
语句)。有人可以帮忙吗?
简单的事情
list[grepl("\\.plt", names(list))]
应该从你的print.plots
函数给你一个非常接近我想你想要的结果。
至于写一个函数,一些建议。
list
作为对象。在下面的例子中,我将改为使用mylist
。print_plots
使用下划线而不是点。 print.plots
可能会导致S3类的一些问题。在下面的示例中,我们查找将.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