我在for循环中有一个R-markdown文档(测试各种模型),我想用HTML Headers设置它们,因为否则很难找到我正在寻找的模型。有"asis"
选项,但会关闭整个块的格式,这不是我想要的。我尝试了一些我在这里找到的东西,但没有什么真正有效。这是我的代码:
---
title: "Untitled"
author: "Mike Wise - 25 Jul 2014"
date: "November 2, 2015"
output: html_document
---
Test
```{r, echo=T}
for (i in 1:3){
print("<h1>Title</h1>")
#print("##Title")
m <- data.frame(matrix(runif(25),5,5))
print(m)
}
```
以下是一次没有正确标题格式的尝试:
以下是results="asis"
选项的样子:
答案 0 :(得分:1)
您可以尝试使用kable
功能:
```{r, echo=T, results="asis"}
library(knitr)
for (i in 1:3){
print("<h1>Title</h1>")
#print("##Title")
m <- data.frame(matrix(runif(25),5,5))
print(kable(m, format = "html"))
}
```
这给了我:
答案 1 :(得分:1)
试试这个。
```{r, echo=F, results="asis"}
for (i in 1:3){
library(knitr)
print("<h1>Title</h1>")
#print("##Title")
m1 <- knitr::kable(data.frame(matrix(runif(25),5,5)))
print(m1)
}
```
答案 2 :(得分:0)
好的,这是一年半之后,我仍然不时需要这个,但从那时起我就学会了如何正确地做到这一点。您需要编写knitr
&#34;输出挂钩&#34;,并修改输出,以便html可以&#34;转义&#34;通过。
以下内容实现了这一目标:
knitr
输出挂钩。<h1>some_text</h1>
使用htmlesc<<(h1,some_text)>>
h1
和some_text
的正则表达式,并将其重新格式化为正确标记的html,同时删除##
插入的knitr
。h4
,p
,正确放置图表和表格等。)所以这是代码:
---
title: "Output Hook for HTML Escape"
author: "Someone"
date: "2017 M04 25"
output:
html_document:
keep_md: true
---
```{r setup, include=T,echo=TRUE}
knitr::opts_chunk$set(echo = TRUE)
hook_output <- knitr::knit_hooks$get("output")
knitr::knit_hooks$set(output=function(x,options){
xn <- hook_output(x,options)
# interestingly xn is a big character string.
# I had expected a list or vector, but the length of x is 1 and the class is character.
# The following regexp extracts the parameters from a statement of the form
# htmlesc<<(pat1,pat2)>> and converts it to <pat1>pat2</pat1>
xn <- gsub("## htmlesc<<([^,]*),{1}([^>>]*)>>","\n```\n<\\1>\\2</\\1>\n```\n",xn)
# now remove double escaped lines that occur when we do these right after each other
gsub(">\n```\n\n\n```\n<",">\n<",xn)
}
)
```
## An analysis loop in a single R chunk with R Markdown
In the following, we do a loop and generate 3 sets of data:
(@) We have some explanitory text
(@) then we do a bar plot with ggplot
(@) then we print out a table
(@) then we do a base plot - just for fun
```{r, echo=T, fig.height=3,fig.width=5}
library(knitr)
library(tidyr)
library(ggplot2)
set.seed(123)
for (i in 1:3){
mdf <- data.frame(matrix(runif(25),5,5))
cat(sprintf("htmlesc<<h1,Title %d>>\n",i))
cat(sprintf("htmlesc<<h4,Smaller Title - also for %d>>\n",i))
cat(sprintf("htmlesc<<p,and some text talking about this %d example>>\n",i))
print(sapply(mdf,mean))
gdf <- gather(mdf,series,val)
gp <- ggplot(gdf)+geom_bar(aes(series,val,fill=series,color=I("black")),stat="identity")
print(gp)
print(mdf)
plot(mdf)
}
```
这是输出(因为你不需要细节而缩小了一点)。
顺便提一下,这个唯一真实的文件是易辉的优秀编织书,搜索很容易找到。