gpt4 book ai didi

r - 在 html rmarkdown 中嵌入 csv

转载 作者:行者123 更新时间:2023-12-02 20:50:43 30 4
gpt4 key购买 nike

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

...参见 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 ?

最佳答案

没有 JavaScript;没有小部件;没有额外的 CSS; 4 LoC(如果您喜欢不可读的代码,则可以是 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
  • 将其嵌入为 Markdown 链接

您还可以执行以下操作:

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

如果您想为浏览器(以及用户)提供建议的文件名(适用 Markdown 规则中的 HTML 放置)。

注意:

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

readLines() 版本同样有效。

关于r - 在 html rmarkdown 中嵌入 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41196823/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com