我有一个Rmarkdown文档,我想只显示代码块的部分输出。
例如,请考虑以下事项:
```{r echo=1:2, eval=-2, collapse=TRUE}
mod <- lm(speed ~ dist, data = cars)
summary(mod)
out <- capture.output(summary(mod))
cat(c("[...]", out[9:12], "[...]"), sep = "\n")
```
产生
mod <- lm(speed ~ dist, data = cars)
## summary(mod)
## [...]
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 8.28391 0.87438 9.474 0.00000000000144 ***
## dist 0.16557 0.01749 9.464 0.00000000000149 ***
## [...]
但我想获得的是
mod <- lm(speed ~ dist, data = cars)
summary(mod)
## [...]
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 8.28391 0.87438 9.474 0.00000000000144 ***
## dist 0.16557 0.01749 9.464 0.00000000000149 ***
## [...]
查看summary(mod)
的不同格式。
答案 0 :(得分:2)
以下是我的问题的解决方案
---
output: html_document
---
```{r, echo=FALSE}
library(knitr)
# the default output hook
hook_output <- knit_hooks$get('output')
knit_hooks$set(output = function(x, options) {
if (!is.null(n <- options$out.lines)) {
n <- as.numeric(n)
x <- unlist(stringr::str_split(x, "\n"))
nx <- length(x)
x <- x[pmin(n,nx)]
if(min(n) > 1)
x <- c(paste(options$comment, "[...]"), x)
if(max(n) < nx)
x <- c(x, paste(options$comment, "[...]"))
x <- paste(c(x, "\n"), collapse = "\n")
}
hook_output(x, options)
})
```
```{r collapse=TRUE, out.lines = 9:12}
mod <- lm(speed ~ dist, data = cars)
summary(mod)
```
```{r collapse=TRUE, out.lines = 1:3}
summary(mod)
```
```{r collapse=TRUE, out.lines = 17:18}
summary(mod)
```
```{r collapse=TRUE, out.lines = 1:20}
summary(mod)
```
答案 1 :(得分:1)
knitr example 052应该为您提供基本想法:定义output
挂钩,您可以以任何方式操作文本。
knitr::knit_hooks$set(output = function(x, options) {
# manipulate x here
})