如何在 R 中包装函数以实现可见性?

问题描述 投票:0回答:1

将 R Markdown 文件编织为 pdf 会导致行被切断。为了包装它们,我添加了以下包装输出文本的代码。但是,我还想包装代码和函数,以便它们以 pdf 格式可见。

library(knitr)
hook_output = knit_hooks$get('output')
knit_hooks$set(output = function(x, options) {
  # this hook is used only when the linewidth option is not NULL
  if (!is.null(n <- options$linewidth)) {
    x = xfun::split_lines(x)
    # any lines wider than n should be wrapped
    if (any(nchar(x) > n)) x = strwrap(x, width = n)
    x = paste(x, collapse = '\n')
  }
  hook_output(x, options)
})

这会包装函数输出,但该函数仍在页面上运行。按 Enter 键使其出现在多行上会导致 正在打印。有没有办法摆脱这个 同时仍允许以 pdf 格式完整查看功能代码?在下面的示例中,我按 sprintf 函数的 Enter 键以将其全部显示在页面上。但现在有一个不受欢迎的情况 在输出中。

enter image description here

r printing word-wrap
1个回答
0
投票

输出钩子只会处理块的输出。要包装源代码,您必须添加一个

source
钩子:

---
output: pdf_document
date: "2024-05-01"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
library(knitr)

wrap_helper <- function(x, options) {
  if (!is.null(n <- options$linewidth)) {
    x <- xfun::split_lines(x)
    if (any(nchar(x) > n)) x <- strwrap(x, width = n)
    x <- paste(x, collapse = "\n")
  }
  x
}

hook_output <- knit_hooks$get("output")
knit_hooks$set(output = function(x, options) {
  hook_output(wrap_helper(x, options), options)
})

hook_source <- knitr::knit_hooks$get("source")
knit_hooks$set(source = function(x, options) {
  hook_source(
    wrap_helper(x, options),
    options
  )
})
```

```{r linewidth=40}
sprintf("nunc aptent eu viverra habitant imperdiet ante ultricies tristique convallis nunc aptent eu viverra habitant imperdiet ante ultricies tristique convallis")
``` 

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.