在html rmarkdown中嵌入csv

时间:2016-12-17 08:37:57

标签: r csv r-markdown

  • 示例
  • 问题陈述
  • 解决方案搜索和
  • 问题

...请参阅rmarkdown示例代码。

通过修改rmarkdown片段来欣赏证明该解决方案的答案。

---
title: "Reproducable Example"
author: "user2030503"
output: html_document
---

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

## Example: mtcars

```{r}
write.csv2(mtcars, "./file.csv")

# Code to embed mtcars as csv
# Code to provide mechanism for button or link for later user interaction to open/save the csv. 
```

## Problem

* I want to embed the csv file into the html generated by this rmarkdown script.
* Embedding here means, that the csv data are integral part of the hmtl (i.e. for offline use).
* I want a mechanism (button or link) in the html, which allows the user to open/save the data the csv.

## Search for a solution

There are techniques for embedding rdata files.

* http://rmarkdown.rstudio.com/articles_rdata.html
* https://github.com/richarddmorey/BayesFactorExtras/blob/master/BayesFactorExtras/R/downloadURI.R

## Question

* Dispite of above approaches, I did not find a solution yet how to solve the problem.
* How can it be achieved demonstrating it via this reproducable example ?

3 个答案:

答案 0 :(得分:17)

没有javascript;没有小工具;没有额外的CSS; 4 LoC(如果你喜欢不可读的代码,则cld为1 LoC):

```{r}
write.csv2(mtcars, "./file.csv")

library(magrittr)
readLines("./file.csv") %>% 
  paste0(collapse="\n") %>% 
  openssl::base64_encode() -> encoded
```

[Download CSV](`r sprintf('data:text/csv;base64,%s', encoded)`)

相当简单:

  • 将文件视为“东西”,并将其作为行
  • 读取
  • 将所有新行分隔的文本设为
  • 将其编码为base 64
  • 使用适当的媒体类型制作数据URI
  • 将其嵌入为降价链接

您还可以执行以下操作:

<a download="mtcars.csv" href="`r sprintf('data:text/csv;base64,%s', encoded)`">Straight HTML Download Link</a>

如果您想为浏览器(以及用户)提供建议的文件名(适用于降价规则中的HTML展示位置)。

注:

readBin("./file.csv", "raw", file.info("./file.csv")$size) %>% 
  openssl::base64_encode() -> encoded

readLines()版本同样有效。

答案 1 :(得分:3)

这样的事情怎么样:

---
title: "Reproducable Example"
author: "dimitris_ps "
date: "17 December 2016"
output: html_document
---

<style>
  #DataTables_Table_0 {
     visibility: hidden;
  }

  #DataTables_Table_0_paginate {
    visibility: hidden;
  }

</style>

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

dt <-   datatable(mtcars, rownames=T, 
            # filter = 'top',
              callback=JS('$("a.buttons-collection").css("background","#008CBA");
           $("a.buttons-collection").css("font-size","15px");
           $("a.buttons-collection").css("border-radius", "8px");
           $("a.buttons-collection").css("margin-right","0px");
           return table;'),
        extensions = 'Buttons',
        options = list(searching=F,
                       paging = T,
                       bInfo = F,
                       columnDefs = list(list(className = 'dt-left',  targets = 0),
                                         list(className = 'dt-center',  targets = 1:11)),
                       pageLength = 1,
                       initComplete = JS("function(settings, json) {",
                                         "$(this.api().table().header()).css({'background-color': '#99ccff', 'color': '#003333'});",
                                         "}"),
                       dom = 'Bfrtip',
                       buttons = list(
                                      list(extend = 'collection',
                                           buttons = c('excel', 'csv'),
                                           text = 'DOWNLOAD DATA')
                       )
        )
  )

```
<br>

```{r mtcars, echo=FALSE}
dt
```

您需要安装DT

答案 2 :(得分:2)

根据用户hrbrmstr的answer,我准备了一个便利函数embed_data(),看看它的实际效果:

---
title: "Untitled"
author: "user2030503"
date: "17 12 2016"
output: html_document
---

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

```{r echo=FALSE}

embed_data= function(x= mtcars, filename= "file.csv", label= "Get data"){

  # Create encoded Base64 datastream 
  encode_data= function(x){
    write.csv2(x, "./file.csv")
    enc= sprintf('data:text/csv;base64,%s', openssl::base64_encode(paste0(readLines("./file.csv"), collapse="\n")) )
    unlink("./file.csv")
    return(enc)
  }

  # String result ready to be placed in rmarkdown
  paste0("<a download='", filename, "' href=", encode_data(x), ">", label, "</a>")

}
```

`r embed_data(mtcars, filename="mtcars.csv")`