Reputation: 96
I have an Rmarkdown document and I would like to show only partial output from a code chunk.
For example, consider the following:
```{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")
```
which produces
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 ***
## [...]
but what I would like to obtain is
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 ***
## [...]
See the different format of summary(mod)
.
Upvotes: 1
Views: 1397
Reputation: 96
Here is the solution for my problem
---
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)
```
Upvotes: 2
Reputation: 30104
The knitr example 052 should give you the basic idea: define the output
hook, and you can manipulate the text in any way you want.
knitr::knit_hooks$set(output = function(x, options) {
# manipulate x here
})
Upvotes: 1