我正在使用下面的设置来创建一个ggplot2图表列表。
这样做的效果很好:
library(grid)
library(gridExtra)
library(ggplot2)
mycols <- c('year','displ')
mylist <- list()
for(item in mycols){
p <- ggplot(mpg, aes_string(x = 'hwy', y = item)) +
geom_point()
mylist[[(length(mylist) +1)]] <- p
}
ml = marrangeGrob(grob = mylist, nrow=2, ncol=1)
ggsave("P://multipage.pdf", ml, width =10, height = 5)但是,在循环中,替换:
mylist[[(length(mylist) +1)]]与mylist <- append(mylist, p) 如何在不跟踪索引的情况下将元素附加到列表中?将在ggsave阶段抛出一个错误:
$<-.data.frame中的错误(*tmp*,"wrapvp",value = list(x = 0.5,y=0.5):替换有17行,数据有234个
这里有什么问题?单独而言,列表中的所有图表看起来都很好。
谢谢!
发布于 2017-08-30 17:46:53
这实际上与marrangeGrob无关,也与您如何构建列表有关。比较这些方法的输出结构
out1 <- list()
out1[[length(out1)+1]]<-list(a=1, b=2)
out1[[length(out1)+1]]<-list(a=2, b=2)
str(out1)
# List of 2
# $ :List of 2
# ..$ a: num 1
# ..$ b: num 2
# $ :List of 2
# ..$ a: num 2
# ..$ b: num 2
out2 <- list()
out2 <- append(out2, list(a=1, b=2))
out2 <- append(out2, list(a=2, b=2))
str(out2)
# List of 4
# $ a: num 1
# $ b: num 2
# $ a: num 2
# $ b: num 2请注意,它们产生不同的结构。append()将元素添加到“根”列表中,而不是嵌套列表中的列表。您可以使用和额外的list()显式地自己做这件事。
out3 <- list()
out3 <- append(out3, list(list(a=1, b=2)))
out3 <- append(out3, list(list(a=2, b=2)))
str(out3)
# List of 2
# $ :List of 2
# ..$ a: num 1
# ..$ b: num 2
# $ :List of 2
# ..$ a: num 2
# ..$ b: num 2但是,像这样在R中搅乱循环很少是必要的。最好使用内置迭代器,如lapply()或Map()。例如
mylist <- lapply(mycols, function(item) {
ggplot(mpg, aes_string(x = 'hwy', y = item)) +
geom_point()
})https://stackoverflow.com/questions/45966069
复制相似问题