RMarkdown Chunk - do not reflect the last expression

I have a piece in an RMarkdown document that looks like this:

```{r, echo=-4}
a <- 1
b <- 2
x <- a + b
print(paste(c("`x` is equal to ", x), collapse=""))
```

When I knit this, it does not display the fourth expression as expected, and as described here .

a <- 1
b <- 2
x <- a + b
## [1] "`x` is equal to 3"

However, if I add another line inside the fragment, I need to update the parameter echoor it hides the wrong expression:

```{r, echo=-4}
a <- 1
b <- 2
c <- 3
x <- a + b + c
print(paste(c("`x` is equal to ", x), collapse=""))
```

Conclusion:

a <- 1
b <- 2
c <- 3
print(paste(c("`x' is equal to ", x), collapse=""))
## [1] "`x` is equal to 6"

Is there a programmatic way in the RMarkdown block to indicate that you do not want to echo the last expression in a piece without manually counting the total number of lines?

+4
source share
3 answers

: knitr hooks, , , .
chunk rm.last, n .
knitr , knitr::knit_hooks$get('source').

---
title: "Hack the output with hooks"
---

```{r setup, include=FALSE}
knitr::opts_hooks$set(rm.last = function(options) {
  options$code <- 
    paste0(
      options$code, 
      c(rep("", length(options$code) - options$rm.last), 
        rep(" # REMOVE", options$rm.last)
      )
    )
  options
})

builtin_source_hook <- knitr::knit_hooks$get('source')

knitr::knit_hooks$set(source = function(x, options) {
  if (!is.null(options$rm.last))  
    x <- grep("# REMOVE$", x, invert = TRUE, value = TRUE)
  if (length(x) > 0) {
    return(builtin_source_hook(x, options))
  } else {
    invisible(NULL)
  }
})
```

```{r, rm.last=1}
a <- 1
b <- 2
x <- a + b
print(paste(c("`x` is equal to ", x), collapse=""))
```

, print(...), , , @atiretoo.

+3

```{r}
a <- 1
b <- 2
x <- a + b
```

`x` is equal to `r x`

.

+3

, . knitr, , ,

code = code[options$echo]

Therefore, regular indexing is used to select records. R. R does not have the ability to say "last element" in a constant value or a vector of values, rmarkdownand therefore knitrthey have no way to say "last expression". Using the @atiretoo clause (just put it in a separate snippet) seems like the best choice.

+2
source

Source: https://habr.com/ru/post/1695485/


All Articles