Search code examples
rlatexknitrsweave

Abbreviating long R output in knitr


I remember that I've seen a hook in knitr to abbreviate R output. But I forgot how to accomplish this task. How can I show first few lines and last few lines of R output connected with ellipses (...).

   \documentclass{article}
    \begin{document}

    << Test >>=
    1:1000
    @
    \end{document}

I found this link but it does not work for me.

Edited

@kohske solution is excellent and works fine if there is only one output. Need more generalization for such Chunk.

<< label=Test, results = "hold" >>=
1:1000
args(lm)
@ 

Solution

  • Is this what you want?

    \documentclass{article}
    \begin{document}
    
    <<include=FALSE>>=
    library(knitr)
    oh <- knit_hooks$get("output")
    knit_hooks$set(output = function(x, options) {
      ret <- strsplit(x, "\n")[[1]]
      ret <- paste0(ret[1], "\n...\n", ret[length(ret)])
      oh(ret, options)
    })
    @
    
    
    << Test>>=
    1:1000
    @
    \end{document}
    

    enter image description here

    UPDATE

    knit_hooks$set(output = function(x, options) {
      ret <- strsplit(x, "\n")[[1]]
      ret <- if (length(ret) > 2)
        paste0(ret[1], "\n...\n", ret[length(ret)])
      else
        ret
      oh(ret, options)
    })