gpt4 book ai didi

单行 R-markdown block 内的 HTML 代码

转载 作者:行者123 更新时间:2023-11-27 23:36:57 25 4
gpt4 key购买 nike

我在 for 循环中有一个 R-markdown 文档(测试各种模型),我想用 HTML Headers 关闭它们,否则很难找到我正在寻找的模型。有 "asis" 选项,但它会关闭整个 block 的格式,这不是我想要的。我已经尝试了一些我在这里找到的东西,但没有任何效果。这是我的代码:

---
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)
}
```

这是一种没有正确标题格式的尝试:

enter image description here

下面是 results="asis" 选项的样子:

enter image description here

最佳答案

好吧,一年半过去了,我仍然不时需要这个,但从那以后我学到了足够多的知识,知道如何正确地做它。你需要写一个 knitr “输出 Hook ”,并修改输出,以便 html 可以“转义”通过。

以下实现了这一点:

  • 添加了 knitr输出 Hook 。
  • 定义了一种语法来指定所需的标签和内容
    • 例如获取<h1>some_text</h1>使用 htmlesc<<(h1,some_text)>>
  • 想出一个提取 h1 的正则表达式和 some_text并将其重新格式化为正确标记的 html,删除 ##knitr也插入了。
  • 添加了更多测试用例以确保它做了一些额外的事情(例如 h4p 、图表和表格的正确放置等)
  • 添加了另一个正则表达式以删除双转义行,这些行添加了一些不需要的空白镶板结构。

代码如下:

---
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)
}
```

这是输出(由于您不需要详细信息而缩小了一点)。

enter image description here

顺便说一下,唯一真正的文档是 Yihui 的优秀 knitr 书,搜索很容易找到它。

关于单行 R-markdown block 内的 HTML 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33478874/

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