Hiding selected lines in code chunk

Hello, I'm new to RStudio. I'm trying to hide last line in the code chunk with indexing, but it's not working. Is there any way to hide the last line? echo = -5 doesn't work as well.

```{r, echo=1:4}
new_revenue_data %>%
  filter(Year >= 2018) %>%
  arrange(Year) %>%
  head() %>%

Hi there!

You can have a look here: r - RMarkdown Chunk - Don't echo last expression - Stack Overflow

As you can see there are some ways to get around it but it won't work for all circumstances. Let me know if this helps/solves your problem :slight_smile:

Unfortunately it didn't work. I've tried few things to understand how echo works. It seems that echo doesn't work with the pipe operators :confused:

Hi there,

I performed a reprex with your problem and it works.

See screenshot:

See code:

title: "Hack the output with hooks"

knitr::opts_hooks$set(rm.last = function(options) {
  options$code <- 
      c(rep("", length(options$code) - options$rm.last), 
        rep(" # REMOVE", options$rm.last)

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 {
a <- 1
b <- 2
x <- a + b
print(paste(c("`x` is equal to ", x), collapse=""))


output <- 
  mtcars %>%
  filter(mpg >= 21) %>%
  arrange(mpg) %>%
  head() %>%


As you will see we only have library(tidyverse) loading while the last 5 lines got disabled via rm.last=5.

It is tuff to paste the code without chunks etc vanishing. See full screenshot here for code:

Thank you very much for your work, however I don't understand how rm.last works. Why all the output assignment have disappeared? I count the last 5 lines so i think it should output until the line with "mtcars".

If the aim is to print the the output of a chunk with kable without having to show kable in the source chunk, you can use the df_print method.

title: "test"
    df_print: kable


mtcars %>%
  filter(mpg >= 15) %>%
  arrange(cyl) %>%

echo = 1:4 will not work in your example because your are using the pipe %>%, and the all chain is accounted for 1 expression I think.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.