使用knitr的块的动态调用数 [英] Dynamic number of calls to a chunk with knitr

查看:72
本文介绍了使用knitr的块的动态调用数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个列表:

> lSlopes
$A
  Estimate 2.5 % 97.5 %
1     2.12 -0.56   4.80

$B
  Estimate 2.5 % 97.5 %
1     2.21 -0.68   5.10

$C
  Estimate 2.5 % 97.5 %
1     2.22 -2.21   6.65

它具有三个元素,但是其长度可以更改(根据此处未显示的数据).我想在一个块中显示每个元素.

It has three elements but its length can change (according to the data not shown here). I want to display each element in a chunk.

我的第一个想法是编写一个包含每个步骤都调用knit_child()的循环的块,但是我不知道如何使用knit_child()获得正确的呈现.

My first idea was to write a chunk containing a loop calling knit_child() at each step, but I don't know how to get the correct rendering with knit_child().

我发现以下解决方案效果很好,但需要两个Rmd文件;第一个调用第二个,第二个递归调用自己:

I have find the following solution which works well but which requires two Rmd files; the first one calls the second one and the second one recursively calls itself:

mainfile.Rmd :

```{r, echo=FALSE}
J <- length(lSlopes)
i <- 1
```

```{r child, child="stepfile.Rmd"}
```
Nice!

stepfile.Rmd :

```{r, echo=FALSE}
lSlopes[[i]]
i <- i+1
```

```{r child, child="stepfile.Rmd", eval= i <= J}
```

这恰好生成了我想要的渲染:

This exactly generates the rendering I want:

我喜欢这个棘手的解决方案,但我想知道是否存在非递归解决方案?

I love this tricky solution but I wonder whether there exists a non-recursive solution ?

推荐答案

下面是RMarkdown解决方案,类似于

Below is the RMarkdown solution analogous to https://github.com/yihui/knitr-examples/blob/master/020-for-loop.Rnw, using knit_child(). As my solution, it requires two files, but it is much more clear.

主文件.Rmd:

```{r, echo=FALSE}
J <- length(lSlopes)
```

```{r runall, include=FALSE}
out <- NULL
for (i in 1:J) {
  out <- c(out, knit_child('stepfile.Rmd'))
}
```

`r paste(out, collapse = '\n')` 

Nice!

stepfile.Rmd:

```{r, echo=FALSE}
lSlopes[[i]]
```

这篇关于使用knitr的块的动态调用数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆