gpt4 book ai didi

r - Knitr:for 循环中每个 .tabset 的一个图

转载 作者:行者123 更新时间:2023-12-04 18:33:51 25 4
gpt4 key购买 nike

长话短说,我正在尝试使用 knitr 来动态创建单独的标签集并在每个标签集内渲染一个图。下面是我失败尝试的描述。我希望有一个解决方案,但我怀疑我只是不了解 knitr 呈现输出的基本方式。因此,如果您能给我指出资源或提供一些概念性指导,那也将不胜感激。

动态创建标签集本身很容易。这是我的 .R 文件

#' ---
#' title:
#' author:
#' date:
#' output:
#' html_document
#' ---

#' # {.tabset}
#+ results='asis', echo=FALSE
for(i in 1:10){
cat('##',i,' \n')
}

当我在这个 .R 文件上调用 rmarkdown::render() 时,我得到 10 个空的标签集(见下文)。我不太确定 cat 做什么或为什么\n 是必要的(这是一些概念性解释会受到赞赏的地方),但它有效。
enter image description here
现在我在 for 循环中添加一个 boxplot() 调用,并期望在每个标签集上获得相同的 boxplot。
#' ---
#' title:
#' author:
#' date:
#' output:
#' html_document
#' ---

#' # {.tabset}
#+ results='asis', echo=FALSE
for(i in 1:10){
cat('##',i,' \n')
boxplot(iris$Sepal.Length~iris$Species)
}

但相反,第一个选项卡是空的,第二个选项卡是输出的呕吐物。
enter image description here

如果我添加另一个带有两个“\n”字符的 cat(),则所有选项卡都会出现,但只有第二个选项卡填充了图表。其他选项卡是空的。
#' ---
#' title:
#' author:
#' date:
#' output:
#' html_document
#' ---

#' # {.tabset}
#+ results='asis', echo=FALSE
for(i in 1:10){
cat('##',i,' \n')
boxplot(iris$Sepal.Length~iris$Species)
cat(' \n \n')
}

enter image description here

最佳答案

所以我找到了一个解决方案,但仍然不知道它为什么有效。将不胜感激任何反馈。在每个 plot() 工作之前添加 plot.new() 。

#' ---
#' title:
#' author:
#' date:
#' output:
#' html_document
#' ---

#' # {.tabset}
#+ results='asis', echo=FALSE
for(i in 1:10){
cat('##',i,' \n')
plot.new()
boxplot(iris$Sepal.Length~iris$Species)
cat(' \n \n')
}

关于r - Knitr:for 循环中每个 .tabset 的一个图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36458193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com