gpt4 book ai didi

r - R Markdown 中的网格布局

转载 作者:行者123 更新时间:2023-12-02 03:22:10 26 4
gpt4 key购买 nike

是否有一种干净的方法可以在 rmarkdown 中“平铺”或创建某种类似表格的布局?例如,在 RShiny 中,您可以设置一个排序网格,然后将元素(例如文本、表格、绘图等)放置在这些插槽中以真正控制您的外观。如果 markdown 不是最好的方式,我愿意接受 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 输出的一种解决方法,可自动决定需要多少列。这种方法基于调整 block 钩子(Hook)来改变 Markdown 输出。我们基本上只是执行字符串操作(搜索和替换)。我希望代码中的注释足够干净:

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

enter image description here

关于r - R Markdown 中的网格布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54441565/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com