Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed csv in html rmarkdown

Tags:

r

csv

r-markdown

  • Example
  • Problem statement
  • Solution search and
  • Question

... see rmarkdown example code.

Appreciate answers demonstrating the solution by modifying the rmarkdown snippet.

---
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 ?
like image 695
user2030503 Avatar asked Dec 17 '16 08:12

user2030503


People also ask

How do I write HTML in R Markdown?

To transform your markdown file into an HTML, PDF, or Word document, click the “Knit” icon that appears above your file in the scripts editor. A drop down menu will let you select the type of output that you want. When you click the button, rmarkdown will duplicate your text in the new file format.

How do I show output in R Markdown?

If you prefer to use the console by default for all your R Markdown documents (restoring the behavior in previous versions of RStudioRStudioRStudio is an integrated development environment for R, a programming language for statistical computing and graphics. It is available in two formats: RStudio Desktop is a regular desktop application while RStudio Server runs on a remote server and allows accessing RStudio using a web browser.https://en.wikipedia.org › wiki › RStudioRStudio - Wikipedia), you can make Chunk Output in Console the default: Tools -> Options -> R Markdown -> Show output inline for all R Markdown documents .

What is knitr in R Markdown?

Creating documents with R Markdown starts with an . Rmd file that contains a combination of markdown (content with simple text formatting) and R code chunks. The . Rmd file is fed to knitr, which executes all of the R code chunks and creates a new markdown (. md) document which includes the R code and its output.


2 Answers

No javascript; no widgets; no extra CSS; 4 LoC (cld be 1 LoC if you like unreadable code):

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

Fairly straightforward:

  • treat the file as just "stuff" and read it in as lines
  • make it all one blob of newline separated text
  • encode it into base 64
  • make a data URI with the proper media type
  • embed it as a markdown link

You can also do something like:

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

if you want to give browsers (and, hence, users) a suggested filename (HTML placement in markdown rules apply).

NOTE:

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

also works equally as well as the readLines() version.

like image 138
hrbrmstr Avatar answered Sep 20 '22 18:09

hrbrmstr


How about something like this:

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

You will need to have the DT library installed

like image 35
dimitris_ps Avatar answered Sep 20 '22 18:09

dimitris_ps