【问题标题】:Grid Layout in an R MarkdownR Markdown 中的网格布局
【发布时间】:2019-01-30 13:19:54
【问题描述】:

在 rmarkdown 中是否有一种干净的方式来“平铺”或创建某种类似表格的布局?例如,在 RShiny 中,您可以设置各种网格,然后在这些插槽中放置元素(例如,文本、表格、绘图等)以真正控制您的外观。如果降价不是最好的方式,我愿意接受 HTML、Word 或 PDF 格式的输出。例如,考虑这个文件:

---
title: "Test File"
output: html_document
---

## R Markdown

How do put these side-by-side?

```{r text, echo=FALSE}
summary(cars)
```

```{r plot, echo=FALSE}
plot(speed ~ dist, cars)
```

我可以将summary() 输出放在plot() 输出旁边吗?如果我想去三宽怎么办:plot() | summary() | summary?

我也愿意接受另一种格式/结构。我已经尝试过officer,但很难在 Word 中实现这种对齐方式。

【问题讨论】:

  • 我想列可能就是答案。我希望有更多的控制权,但我相信我可以想出解决方法
  • 输出类型对于这样的事情很重要:HTML 输出的样式非常简单,因为您可以使用 CSS。 PDF 输出可能需要编写 Latex(或查找其他人编写 Latex 的模板)和 Word……我什至不知道。它们都使用非常不同的机制从 Rmarkdown 编译。 Shiny 创建 HTML 文档,因此它可以使用 CSS 样式(我相信通常使用 Bootstrap,它是一个基于网格的框架)
  • 如果你想要 HTML 输出,你可以试试knitrBootstrap。您也可以调整chunk options。最后一个链接还有一个直接在 Rmarkdown 中添加带有 Bootstrap 类的 HTML 的示例
  • 我听到的是 HTML 可能是最简单的方法。我对实际产生的输出格式相当不可知。因此,如果一个人比另一个人更有利于这一点,那么我认为这就是要走的路。

标签: r r-markdown


【解决方案1】:

这是一个自动决定需要多少列的 HTML 输出的解决方法。这种方法基于调整 chunk hook 以改变 markdown 输出。我们基本上只是执行字符串操作(搜索和替换)。我希望代码中的cmets足够干净:

MRE:

---
title: "Test File"
output: html_document
---

## R Markdown

```{r, include = F}
library(stringi)
defChunkHook <- knitr::knit_hooks$get("chunk")
knitr::knit_hooks$set(chunk = function(x, options) {
  x <- defChunkHook(x, options)
  if(!is.null(options$multi.col)) {
    x    <- gsub("(\n\`\`\`\n##.*?\`\`\`)", "<div>\\1\n</div>", x)  # wrap div around output chunks
    x    <- gsub("(<img.*?>)", "<div>\\1\n</div>", x)               # wrap div around plots
    ncol <- nrow(stri_locate_all(x, regex = "<div.*?>")[[1]])       # get the number of div elements created
    x    <- gsub("<div>", paste0("<div style=\"width:", 100/ncol,"%;\">"), x)  # add the width to the divs
    x    <- paste0("<div class=\"multi-col\" style=\"display: flex; justify-content: center; align-items: center;\">\n", x, "</div>")  # wrap the mother div around all of the output
  }
  x
})
```

```{r, echo = F, multi.col=T}
summary(cars)
plot(speed ~ dist, cars)
```

```{r, echo = F, multi.col=T}
summary(cars)
plot(speed ~ dist, cars)
plot(mpg ~ hp, mtcars)
```

【讨论】:

    【解决方案2】:

    我刚刚发现的另一种解决方法是使用gridExtra。您可以创建图形、文本对象、表格等,然后非常清晰地定义它们的结构和相对位置。

    https://cran.r-project.org/web/packages/gridExtra/

    优点:易于使用,可大量控制网格。与ggplot2 配合使用效果很好。

    缺点:现在一切都是图像(包括文本)。就放入其中的对象而言,灵活性较低。据我所知,没有交互性。

    因此,我不想将它用于 HTML 对象。有更好的方法。对于 Word 或 PDF 中对空白的相当简单、高度可控的使用,这可能是一种可行的方法。

    【讨论】:

      猜你喜欢
      • 2018-07-20
      • 1970-01-01
      • 2011-10-28
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 2018-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多