Html R Markdown 中的 2 列部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31753897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:52:28  来源:igfitidea点击:

2 column Section in R Markdown

htmlrr-markdown

提问by bryanR

I'm very new at R Markdown and I'm putting together an R Markdown HTML page for some new R users at my work to give them an intro and walk them through some simple demos. While showing off things like headand tail, it ends up looking messy and long because it prints out each output one after the other. I would like them as long as other sections of my .Rmd to be split into two columns. In my research, I came across this question: 2 Column Report in R Markdown - Render HTML aside Data Frame. There was some discussion of workarounds with HTML code but I'm not at that level in HTML or CSS. I did try including

我是 R Markdown 的新手,我正在为我的工作中的一些新 R 用户整理一个 R Markdown HTML 页面,向他们介绍并引导他们完成一些简单的演示。在炫耀headand 之类的东西时tail,它最终看起来凌乱而冗长,因为它一个接一个地打印出每个输出。我希望它们只要我的 .Rmd 的其他部分被分成两列。在我的研究中,我遇到了这个问题:R Markdown 中的 2 Column Report - Render HTML side of Data Frame。有一些关于 HTML 代码的解决方法的讨论,但我在 HTML 或 CSS 方面没有达到那个级别。我确实尝试包括

<div class="columns-2">
</div>

<div class="columns-2">
</div>

from the official rmarkdowndocumentation, but it didn't have any effect

来自官方rmarkdown文档,但没有任何效果

As I was ready to give up, there was a comment on the Stack Overflow question by @Molx saying that you can separate columns with ***, but didn't give any further explanation. I tried it out in a few ways: I included the ***in the middle of my R code chunk, I separated my R code chunks and put the ***between the two. When I did the latter, the ***simply became a horizontal rule and did nothing with columns.

当我准备放弃时,@Molx 对 Stack Overflow 问题发表了评论,说你可以用 分隔列***,但没有给出任何进一步的解释。我尝试了几种方法:我将***R 代码块包含在中间,我将 R 代码块分开并将其放在两者***之间。当我做后者时,the***只是变成了一条水平规则,对列没有任何作用。

I'm hoping to avoid tables and CSS if possible. If anyone has any thoughts on this, I'd appreciate it.

如果可能,我希望避免使用表格和 CSS。如果有人对此有任何想法,我将不胜感激。

回答by rawr

rmarkdown file:

rmarkdown 文件:

#### Put in your css file or directly in rmarkdown

<style>
  .col2 {
    columns: 2 200px;         /* number of columns and width in pixels*/
    -webkit-columns: 2 200px; /* chrome, safari */
    -moz-columns: 2 200px;    /* firefox */
  }
  .col3 {
    columns: 3 100px;
    -webkit-columns: 3 100px;
    -moz-columns: 3 100px;
  }
</style>

#### This section will have three columns

<div class="col3">
**1** one  
**2** two  
**3** three  
**4** four  
**5** five  
**6** six  
**7** seven  
**8** eight  
**9** nine  
</div>

#### This section will have two columns

<div class="col2">
```{r}
head(mtcars)
tail(mtcars)
```
</div>

Gives me this

给我这个

enter image description here

在此处输入图片说明



Edit

编辑

To be more precise with the column elements, you can use a div for each set of elements:

为了更精确地使用列元素,您可以为每组元素使用一个 div:

Rmd file

Rmd 文件

<style>
.column-left{
  float: left;
  width: 33%;
  text-align: left;
}
.column-center{
  display: inline-block;
  width: 33%;
  text-align: center;
}
.column-right{
  float: right;
  width: 33%;
  text-align: right;
}
</style>

#### This section will have three columns

<div class="column-left">
**1** one  
**2** two  
</div>
<div class="column-center">
**3** three  
**4** four  
**5** five  
**6** six  
</div>
<div class="column-right">
**7** seven  
**8** eight  
**9** nine  
</div>

Gives me

给我

enter image description here

在此处输入图片说明

回答by ErrantBard

The custom css solution from rawr is good, but there is another way if you would like even more customisation and avoid explicit css entirely. Since markdown uses Bootstrap-layout we can use Bootstraps grid layout for in-detail-styling:

rawr 的自定义 css 解决方案很好,但如果您想要更多自定义并完全避免显式 css,还有另一种方法。由于 Markdown 使用 Bootstrap-layout,我们可以使用 Bootstrap 网格布局进行详细设计:

The only drawback are a couple of html-tags extra

唯一的缺点是额外的几个 html 标签

Example:

例子:

---
title: "test"
author: "Testperson"
output:
  html_document
---

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

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

<div class = "row">
<div class = "col-md-6">
```{r cars,  warning = FALSE, echo = FALSE, dev=c('svg')}
plot(pressure)
```
</div>
<div class = "col-md-6">
```{r pressure, warning = FALSE, echo=FALSE, dev=c('svg')}
plot(pressure)
```
</div>
</div>

回答by Alison Shelton

If you are exporting to pdf you can do this in the header with includes.

如果您要导出为 pdf,则可以在包含包含的标题中执行此操作。

Without using css files I have created a two-column environment using the following.

在不使用 css 文件的情况下,我使用以下内容创建了一个两列环境。

1st: I created the file header.tex. header.texincludes the following statements:

第一:我创建了文件header.tex. header.tex包括以下声明:

\usepackage{multicol}
\newcommand{\btwocol}{\begin{multicols}{2}}
\newcommand{\etwocol}{\end{multicols}}

2nd: I put the following command into my document header

第二:我将以下命令放入我的文档标题中

---
title: "My title"
author: "My name"
date: "Today"
output:
    beamer_presentation:
        highlight: haddock
    includes:
        in_header: header.tex
        keep_tex: yes
---

Here is an example of the body and a picture of the output with two columns.

这是正文的示例和具有两列的输出图片。

***********
\btwocol
```{r, results="asis"}
print("test")
```

Here is some text that also is in two column environment.
\etwocol

Now only one column

And here is what the slide looks like: enter image description here

这是幻灯片的样子: 在此处输入图片说明

回答by Grant

Update (May 2020)

更新(2020 年 5 月)

Pandoc now supports a fenced_divapproach for specifying environments. This is also the approach that the R Markdown Cookbookrecommendsfor multi-column environments, with some special tweaks to the preamble files.

Pandoc 现在支持用于指定环境的fenced_div方法。这也是R Markdown Cookbook为多列环境推荐的方法,对前导文件进行了一些特殊调整。

I've updated my original linked example (below) to reflect this best practice... but I've also packaged an R Markdown templatethat bundles together the necessary preamble files. A MWE with this fenced div approach might look like this:

我已经更新了我的原始链接示例(如下)以反映这种最佳实践......但我还打包了一个R Markdown 模板,将必要的前导文件捆绑在一起。使用这种围栏 div 方法的 MWE 可能如下所示:

---
title: "Two column test"
output:
  html_document:
    css: preamble.css
  pdf_document:
    includes:
      in_header: preamble.tex
---

This is regular text spanning the whole page. But here comes a two-column section.

:::::: {.columns}
::: {.column width="48%" data-latex="{0.48\textwidth}"}
This text is in the left column.
:::
::: {.column width="4%" data-latex="{0.04\textwidth}"}
\ 
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="48%" data-latex="{0.48\textwidth}"}
This text is in the right column.
:::
::::::
\newline

And back to a regular single-column environment.

Original answer

原答案

A late contribution to this thread, but just to point out that you can combine @rawr and @Alison's answers to enable multicolumn sections for bothHTML and PDF. R Markdown/knitr is smart enough to parse only the relevant commands depending on the desired output format. I'm often knitting the same document to multiple formats, so this is very convenient. Here is a fully developed example.

此主题逾期的贡献,但只是想指出,你可以结合@rawr和@艾莉森的答案启用多列部分HTML和PDF。R Markdown/knitr 足够智能,可以根据所需的输出格式仅解析相关命令。我经常将同一个文档编织成多种格式,所以这很方便。这是一个完全开发的示例

回答by algoquant

The CSS solution for creating multiple columns doesn't allow for controlling where the column breaks occur. It appears that column breaks are inserted automatically to distribute content evenly between the columns, which isn't always what you may want.
The "***" symbols in markdown and rmarkdown insert a horizontal line break, not a new column.

用于创建多列的 CSS 解决方案不允许控制发生列中断的位置。似乎自动插入分栏符以在列之间均匀分布内容,这并不总是您可能想要的。
markdown 和 rmarkdown 中的“***”符号插入水平换行符,而不是新列。

Besides the .Rmd format for slide presentations, Rstudio also provides a .Rpres slide presentation format (Rpresentations). Rpresentations use a slightly different flavor of markdown, where the "***" symbols insert a new column.

除了用于幻灯片演示的 .Rmd 格式,Rstudio 还提供了 .Rpres 幻灯片演示格式 (Rpresentations)。Rpresentations 使用略有不同的 Markdown 风格,其中“***”符号插入一个新列。

Below are links to an introduction to Rpresentations by RStudio:
Two Column Layouts
Authoring R Presentations

以下是 RStudio 对 Rpresentations 的介绍的链接:
两列布局
创作 R 演示文稿

Below are links to StackOverflow questions similar to yours:
Two Column Layouts in RStudio
Two Column Layouts in markdown

以下是类似于您的 StackOverflow 问题的链接:
RStudio 中的两列布局Markdown 中的
两列布局

The biggest drawback of the Rpresentation format is that it doesn't support embedded shiny applications for interactive visualizations. But Rpresentation does support interactive webgl plots. Below is a simple example. You can save it into an .Rpres file, open it in RStudio, and compile it into an HTML slide presentation. Note the interactive webgl plot in the last slide, that you can manipulate with your mouse.

Rpresentation 格式的最大缺点是它不支持用于交互式可视化的嵌入式闪亮应用程序。但是 Rpresentation 确实支持交互式 webgl 图。下面是一个简单的例子。您可以将其保存为 .Rpres 文件,在 RStudio 中打开它,然后将其编译为 HTML 幻灯片演示文稿。请注意最后一张幻灯片中的交互式 webgl 图,您可以使用鼠标进行操作。

Simple R Presentation
========================================================
title: "Simple R Presentation"
author: John Doe
date: `r format(Sys.time(), "%m/%d/%Y")`
width: 1900
height: 1000
```{r setup, include=FALSE}
# This is an R setup chunk, containing default options applied to all other chunks
library(knitr)
# This sets the chunk default options
opts_chunk$set(cache=TRUE, collapse=TRUE, error=FALSE, prompt=TRUE)
# This sets the chunk display theme
thm <- knit_theme$get("acid")
knit_theme$set(thm)
# This sets some display options
options(digits=3)
options(width=80)
```


My First Slide
========================================================
Hello World!  
Creating Rpresentations isn't difficult at all!  

<img src="https://community.filemaker.com/servlet/JiveServlet/showImage/2-180549-7694/staples-easy-button.png" width="500" height="500" />


***

The Cauchy-Schwarz Inequality:  

$$
\left( \sum_{k=1}^n a_k b_k \right)^2 
\leq 
\left( \sum_{k=1}^n a_k^2 \right) 
\left( \sum_{k=1}^n b_k^2 \right) 
$$



Slide With R Code Chunk and Output in Two Columns
========================================================

First column contains simple R code that returns the summary of the cars data frame:  
```{r, summ_cars, eval=FALSE, echo=TRUE, results="hold", size="tiny"}
summary(cars)
```
***
Second column contains the output of the code in the first column:  
```{r, summ_cars, eval=TRUE, echo=FALSE, size="tiny"}
```



Slide With Plot
========================================================

First column with R code:  
```{r, plot_cars, eval=TRUE, echo=(-(1:1)), fig.show="hide"}
par(cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5)
plot(cars)
```

***

Second column with plot:  
```{r, plot_cars, eval=TRUE, echo=FALSE, fig.width=10, fig.height=8}
```



Slide with Interactive 3d Surface Plot
========================================================

First column with R code:  
```{r, rgl_surf3d, eval=FALSE, echo=TRUE, webgl=TRUE, fig.show="hide"}
library(rgl)  # load rgl
knit_hooks$set(webgl=hook_webgl)
# define function of two variables
foo <- function(x, y) y*sin(x)
# draw 3d surface plot of function
persp3d(x=foo, xlim=c(-5, 5), ylim=c(-5, 5), col="green", axes=FALSE)
```

***

Second column with plot:  
```{r, rgl_surf3d, eval=TRUE, echo=FALSE, webgl=TRUE, fig.width=10, fig.height=8}
```