简体   繁体   English

在 knitr 中缩写长 R 输出

[英]Abbreviating long R output in knitr

I remember that I've seen a hook in knitr to abbreviate R output.我记得我在knitr看到了一个钩子来缩写R输出。 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 (...) .如何显示与ellipses (...)连接的R输出的前几行和最后几行。

   \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. @kohske 解决方案非常好,如果只有一个输出,则工作正常。 Need more generalization for such Chunk.需要对此类块进行更多概括。

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

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}

在此处输入图片说明

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)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM