r - 数据框到字表?

标签 r r-markdown

有没有办法通过 rmarkdown 轻松地将数据框转换为 Word 表?

如果我在 RStudio 中使用 rmarkdown 创建一个 Word 文档,我会得到一个打印精美的表格,但它不会被识别为 Word 表格。完全可以做到吗?

   ```{r}
   name_of_df
   ```

最佳答案

编辑: ReporteRs 仍在维护,但不会再发展。使用 officerflextable反而 :

library(officer)
library(flextable)
library(magrittr)

# Create flextable object
ft <- flextable(data = mtcars) %>% 
  theme_zebra %>% 
  autofit
# See flextable in RStudio viewer
ft

# Create a temp file
tmp <- tempfile(fileext = ".docx")

# Create a docx file
read_docx() %>% 
  body_add_flextable(ft) %>% 
  print(target = tmp)

# open word document
browseURL(tmp)

结束编辑

嗨,您也可以尝试套餐 ReporteRs 把data.frame转成Word表格,函数是 FlexTable :
library(ReporteRs)
library(magrittr)

docx( ) %>% 
  addFlexTable( mtcars %>%
                  FlexTable( header.cell.props = cellProperties( background.color =  "#003366" ),
                             header.text.props = textBold( color = "white" ),
                             add.rownames = TRUE ) %>%
                  setZebraStyle( odd = "#DDDDDD", even = "#FFFFFF" ) ) %>%
  writeDoc( file = "exemple.docx" )

# open the Word document
browseURL("exemple.docx")

enter image description here

使用 Markdown ,我认为这只适用于 HTML :
---
title: "HTML table"
output: html_document
---

```{r, results='asis'}
library(ReporteRs)
tabl = FlexTable( mtcars,
                  header.cell.props = cellProperties( background.color = "#003366" ),
                  header.text.props = textBold( color = "white" ),
                  add.rownames = TRUE )
tabl = setZebraStyle( tabl, odd = "#DDDDDD", even = "#FFFFFF" )
cat(as.html(tabl))
```

这是关于如何使用 ReporteRs 创建 Word 文档的另一个示例:
library(ReporteRs)
# Create a docx object
doc = docx()
# add a document title
doc = addParagraph( doc, "A FlexTable example", stylename = "TitleDoc" )
# add a section title
doc = addTitle( doc, "How to turn a data.frame into a Word table", level = 1 )
# some text
doc = addParagraph( doc, "We use the mtcars dataset as example.", stylename = "DocDefaults" )
# add a table
MyFTable = FlexTable( data = mtcars[1:10, ], add.rownames = TRUE )
# format body content
MyFTable[3:4, "cyl"] = cellProperties( background.color = "red" )
MyFTable["Valiant", ] = cellProperties( background.color = "blue" )
doc = addFlexTable(doc, MyFTable)
# write the doc
writeDoc( doc, file = "exemple.docx" )
# open the Word doc
browseURL("exemple.docx")

enter image description here

如需更多示例,您可以访问 http://davidgohel.github.io/ReporteRs/word.html

关于r - 数据框到字表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25425993/

相关文章:

r - R中的多线性主成分

r - 在 R 包中包含命令行脚本

database - 为R中数据框中的每一行数据创建哈希值

r - 从.rmd编织到Word时如何格式化表格表格(带书本)

css - Rstudio 0.98.1028 仅将背景图像添加到标题幻灯片

r - Shiny :runExample 给出错误(不能从 `runApp()` 内调用 `runApp()` )

r - 在 R 中放大集群/热图

r - 使用 emphasis.strong.cells 强调单元格失败 - POSIXct 相关?

r - R slidy_presentation 中的两列幻灯片

r - 使用 dplyr::mutate 计算到数据点的地理距离