1

有没有办法在没有环绕格式标签的情况下将 R 代码输出注入到生成的文档<pre><code class="r"><pre><code>?我问这个是因为我想使用 .Rmd 而不是 .Rhmtl 但同时注入一些额外的 HTML 行。使用 eg 这样做cat("HTML code")会失败,因为输出被<pre><code>.

我尝试运行以下 .Rmd 文件(带有额外的 HTML 行)的示例,该文件无法正确运行:

<script type="text/javascript">
<!--
function toggle_visibility(id) {
  var e = document.getElementById(id);
  if(e.style.display == 'none')
    e.style.display = 'block';
  else
    e.style.display = 'none';
}
//-->
</script>  

```{r}
1:10
```

<a onclick="toggle_visibility('answer_1');"><b><u>Antwort anzeigen</b></u></a>
<div id="answer_1" style=display:none>
```{r}
1:10
```
</div>
4

2 回答 2

2

你应该可以用knitr's hooks做到这一点。您可能需要查看源代码以了解 render_markdown() 的默认挂钩是什么:

> library(knitr)
> render_markdown()
> knit_hooks$get('echo')
NULL
> knit_hooks$get('message')
function (x, options) 
{
    if (strict) {
        str_c("\n\n", indent_block(x), "\n")
    }
    else str_c("\n\n```\n", x, "```\n\n")
}
<environment: 0x2a3f590>
> knit_hooks$get('output')
function (x, options) 
if (output_asis(x, options)) x else hook.t(x, options)
<environment: 0x2a3f590>
> knitr:::output_asis
function (x, options) 
{
    is_blank(x) || options$results == "asis"
}
<environment: namespace:knitr>

我不确定 hook.t 到底是做什么的,但请检查一下。

另外,您是否尝试过 asis 选项?我并不完全清楚您希望如何格式化,但您也许可以让它与 asis 一起使用。

你可以用钩子做很多很酷的事情。

于 2012-12-17T22:37:44.177 回答
1

我现在所做的是遵循 darozcig 的建议,我使用了 JS。不过,这个解决方案似乎很乏味。更容易整齐合身的 knitr 会更好!在我完整的 .Rmd 脚本下方。

<script type="text/javascript">
<!--
function toggle_visibility(id) {
  var e = document.getElementById(id); 
  if(e.style.display == 'none')
    e.style.display = 'block';
  else
    e.style.display = 'none';
}

function answer_top(name){
  var injection1 = '<a onclick=toggle_visibility("' + name + '")><b><u>Show answer</b></u></a>\n'
  document.write(injection1 + "\n")
  var injection2 = '<div id="' + name + '"style=display:none>'
  document.write(injection2 + "\n")
}

function answer_bottom() {
  document.write("</div>" + "\n")
}
//-->
</script>  

```{r}
1:10
```

<script type="text/javascript">answer_top("answer1")</script>
```{r}
1:10
```
<script type="text/javascript">answer_bottom()</script>
于 2012-06-13T14:56:10.903 回答