【问题标题】:Split code into several syntactically invalid chunks in R Knitr在 R Knitr 中将代码拆分为几个语法无效的块
【发布时间】:2015-12-14 19:10:05
【问题描述】:

是否可以在代码块中获取非格式化的降价文本?我的目标是在for 循环中显示描述。在下面的示例中,这样的操作会导致将代码分成两个语法上无效的块:

I am using for cycle here
```{r results='hide'}
for(i in 1:5){
  foo()
```

There is a lot of interesting stuff inside
```{r results='hide'}
  bar()
}
```

理想情况下会生成:

我在这里使用for循环

for(i in 1:5){
  foo()

里面有很多有趣的东西

  bar()
}

【问题讨论】:

  • 恶搞它。使用echo = F 放置语法完整的代码块,然后使用eval = F 分解你想要的代码。
  • @Gregor :我希望我的代码被评估。
  • 对,但您只能评估语法上有效的代码。所以你评估的第一个有你所有的代码并且在语法上是有效的,但是有echo = F所以它不会被显示。然后,您可以使用eval = F 以任意数量的块显示您想要的代码。而且,如果你打破了跨块的 for 循环也没关系,因为没有评估意味着没有语法错误。
  • 好的,现在我明白了。好吧,这可能会起作用,但我需要将代码放在那里两次。不过还是谢谢。
  • 您是指类似于Advanced usage of the echo option 部分中描述的功能吗?不知道我是否收到了这个问题,因为你写的是你想把一个块分成几块,但是你显示了不同的代码(而不是其他代码子集的代码)。

标签: r markdown knitr


【解决方案1】:

根据 user2706569 的评论建议,您可以使用名称定义一次代码块并对其进行评估。然后您可以重用代码块,但只回显您想要的行,而不进行评估。

取自Yihui's examples...

The plots from the original evaluation are 
shown, but the code is not echoed here. (To 
omit all of the outputs, check out the 
chunk options such as `include=FALSE`.)

```{r mychunk, echo=FALSE}
## 'ugly' code that I do not want to show
par(mar = c(4, 4, 0.1, 0.1), cex.lab = 0.95, cex.axis = 0.9,
    mgp = c(2, 0.7, 0), tcl = -0.3)
plot(mtcars[, 1:2])
plot(mtcars[, 4:5])

```

Now describe the code as you wish without evaluation.

Here's the first and second lines from the original chunk.

```{r mychunk, echo=1:2, eval=FALSE}
```

Here's the third line.

```{r mychunk, echo=3, eval=FALSE}
```

Here's the fourth line.

```{r mychunk, echo=4, eval=FALSE}
```

Here's the fifth line.

```{r mychunk, echo=5, eval=FALSE}
```

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    相关资源
    最近更新 更多