2016-12-17 90 views
5
  • 問題陳述
  • 解決方案搜索和
  • 問題

...看到rmarkdown示例代碼。CSV嵌入在HTML中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 ? 

回答

11

沒有使用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)`) 

相當簡單:

  • 將這個文件看作只是 「東西」,並在它讀成線
  • 使這一切換行的一個團塊中分離文本
  • 編碼成基部64
  • 使一個數據URI與適當的媒體類型
  • 嵌入它的上午arkdown鏈接

你也可以這樣做:

<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()版本。

+0

不幸的是這種解決方案並不在IE 11(Windows 8的)工作。該解決方案生成的鏈接不會觸發任何內容。它如何被修復? – user2030503

+2

埃,使用真正的瀏覽器;-)看來,這是一個已知的問題與IE 11是腦死亡:http://caniuse.com/#feat=datauri;這意味着你不能爲IE 11嵌入這種類型的數據URI。它看起來像Edge也是大腦死亡。 – hrbrmstr

+0

該解決方案適用於Chrome,但在Safari中,下載不會啓動,我們只能看到瀏覽器上顯示的csv。有沒有解決方法? –

2

怎麼是這樣的:

--- 
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庫安裝

+0

欣賞你的努力。兩個問題:1.是一個小問題:兩個JS函數需要一個DT ::前綴。 2.是一個更大的:我不想顯示一張桌子。你可以重構,只有按鈕保持? – user2030503

+0

在你的第1點,加載'庫(DT)',這是我最初的。感謝您指出。在你的point2上可能有一個解決'css'隱藏表的方法。我會在稍後回來 –

+0

我已經更新了我的答案。不是最好的方法,但接近你正在尋找的東西。基本上,我隱藏''DataTable''css' –

1

基於用戶的answer hrbrmstr我準備了一個方便的功能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")`