1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rmarkdown: for文でtab & DT::datatableを生成する

Last updated at Posted at 2018-01-19

最近Rmarkdownでsummary結果をたくさん出力する機会があったので、
for文でタブと中身 (DT::datatable)をセットで自動生成できるよう、
勉強、もといググった。

成果をメモっておく (何番煎じだろう?)。

(追記:発展版を作成 (Rmarkdown: list in tbl_df からタブセット&タブを自動生成する))

丸パク 参考にさせて頂いたGitのページ
ReportMort/DT-issues-67-datatables-generated-in-a-loop-in-rmd-file

以下、.Rmdファイルの記述例 (summary(df)の出力はtableなので、xtable経由でDTに渡す)

---
title: "test"
author: "hoge"
date: "`r Sys.Date()`"
output: 
  html_document:
    md_extensions: -ascii_identifiers
    toc: true
    toc_float: true  
    toc_depth: 3
---

```{r setup, include=FALSE, echo=FALSE}

library(tidyverse); library(xtable); library(DT); library(knitr)

```

```{r create-datasets, echo=FALSE}

## DT::datatablesのリストを作成。リスト名はタブ名として後で使うことにする。

datasets <- list(cars = cars, iris = iris, ToothGrowth = ToothGrowth) %>% 
  map(~ summary(.) %>% 
        xtable() %>% 
        datatable())

```

```{r create-markdown-chunks-dynamically, include=FALSE}

out = NULL
for (i in 1:length(datasets)) {
  knit_expanded <- paste0("###", 
                          names(datasets)[i],  
                          "\n```{r results='asis', echo=FALSE} \n\n datasets[[", i, "]] \n\n``` \n")
  out = c(out, knit_expanded)
}

```

## dynamically make tabs and datatables {.tabset}

<!--- knit those table chunk statements --> 
`r paste(knit(text = out), collapse = '\n')`


## Let's Enjoy !!

同じ要領でggplot2などもいける (変更箇所のみメモ)。

datasets <- list(cars = cars, iris = iris, ToothGrowth = ToothGrowth) %>%
  map(~ ggplot(., aes_string(names(.)[1], names(.)[2])) + geom_point())
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?