如何解决如何在R Markdown中的列表中打印所有记录的图
这是我在StackOverflow上遇到的第一个问题。如果我做错了,请告诉我以改善下一个问题。
我从R Markdown开始,但在打印带有for循环的记录图时遇到一些麻烦。好吧,在我运行Rmarkdown文件之前,我运行了R函数,该函数生成了几个数据框和图表的列表。
为了简化起见,我在这里仅列出了绘图对象,简化了该列表的可复制示例。
x <- c(1,2,3,4,5)
y <- c(1,5)
plot(x,y)
abline(h=1)
p1.1 <- recordPlot()
plot(x,y)
abline(h=3)
p1.2 <- recordPlot()
plot(x,y)
abline(h=4)
p2.1 <- recordPlot()
plot(x,y)
abline(h=6)
p2.2 <- recordPlot()
lista<-NULL
lista["p1.1"] <- list(p1.1)
lista["p1.2"] <- list(p1.2)
lista["p2.1"] <- list(p2.1)
lista["p2.2"] <- list(p2.2)
save(new_list,file = "Data.RData")
然后我将列表加载到R Markdown文件中,如下所示:
```{r setup}
knitr::opts_chunk$set(echo = TRUE,fig.keep = "all")
load("Data.RData")```
我尝试像这样打印这些图:
```{r,echo=FALSE,results='asis',fig.keep='all'}
for (i in c(1,2)){
for(j in c(1,2)){
print(lista[[paste(paste("p",i,sep=""),j,sep=".")]])
}
}```
当我运行Knitr来获取HTML文件时,结果是只显示了for循环的最后一个图。
我尝试用lapply代替for循环,但是对我来说不起作用。另外,我尝试将replayPlot函数print(replayPlot(lista[[paste(paste(paste("p",".",sep="")]]))
用于相同的结果。
有什么方法可以解决此问题而无需修改先前生成图列表的R函数?
谢谢您的回答。
解决方法
您可以使用带有ggplot
对象列表的语法,但是使用基础plot
对象时,您需要调用plot.new()
,以便列表中的下一个图不不会覆盖上一个:
---
title: "test"
output: html_document
---
## Define plots
```{r}
x <- c(1,2,3,4,5)
y <- c(1,5)
plot.new()
plot(x,y)
abline(h=1)
p1.1 <- recordPlot()
plot.new()
plot(x,y)
abline(h=3)
p1.2 <- recordPlot()
plot.new()
plot(x,y)
abline(h=4)
p2.1 <- recordPlot()
plot.new()
plot(x,y)
abline(h=6)
p2.2 <- recordPlot()
lista<-NULL
lista["p1.1"] <- list(p1.1)
lista["p1.2"] <- list(p1.2)
lista["p2.1"] <- list(p2.1)
lista["p2.2"] <- list(p2.2)
```
# Print list
```{r,echo=F}
for (i in c(1,2)){
for(j in c(1,2)){
# Needed to avoid overwrite
plot.new()
print(lista[[paste(paste("p",i,sep=""),j,sep=".")]])
}
}
```
请注意,您可以简化循环的语法:
for(p in lista) {
plot.new()
print(p)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。