本文へスキップ
からだにいいもの

Rのトピックスを中心に『まだ、まだ、知らない、役に立つ情報?』を発信します。

Rで解析:HTMLコードを依存ゼロで作成「hypertext」パッケージの紹介

本パッケージは、依存がゼロの軽量なHTMLコードの作成が可能です。動的なWebページの生成やAPIレスポンスの構築などに役に立つのではないかと考えます。

パッケージバージョンは1.4.0。Windows 11 x64 (build 26200)のR version 4.6.1で確認しています。

パッケージのインストール

下記コマンドを実行してください。

# パッケージのインストール
install.packages("hypertext")
# パッケージの読み込み
library("hypertext")
スポンサーリンク

コマンド例

詳細はコメント、パッケージのヘルプを確認してください。

htmlコードの表示と保存:renderコマンド

以降のコマンド例ではrenderコマンドでhtmlコードを文字列としてコンソールに表示しています。参考までにranderコマンドを使用し、作業フォルダにhtmlファイルを保存する例を紹介します。保存は上書きまたは追記の設定が可能です。

# サンプルデータを作成
set.seed(123)
x <- 1:10
y <- rnorm(10)

# HTMLドキュメントのDOCTYPE宣言を作成
doctype_html <- doctype()

# ページのタイトルを作成
title_tag <- tags$head(tags$title("からだにいいもの"))
# ヘッダーを作成
header_tag <- tags$header(tags$h1("ようこそ"))

# メインコンテンツを作成
main_content <- tags$body(
  tags$p("これはサンプルページです。"),
  tags$a(href = "https://www.karada-good.net", "リンク")
)

# 全体のHTML構造をタグリストにまとめる
html_structure <- tag_list(doctype_html, title_tag, header_tag, main_content)

# HTMLをファイルに保存 (上書き)
render(html_structure, file = "sample_page.html", write_mode = "overwrite")

# HTMLをファイルに追記
# render(html_structure, file = "sample_page.html", write_mode = "append")

tags(組み込みタグ)の使用例

実行すると、指定されたタグのリストが得られます。

# Hello Worldのタグを定義
tags$p(class = "lead", "Hello, world!")
<p class="lead">Hello, world!</p>
# 入れ子構造のタグをレンダリング
render(tags$div(id = "app", tags$h1("Title")))
[1] "<div id=\"app\"><h1>Title</h1></div>"

既に形式が整えられた文字列を、HTMLとして解釈する例です。

raw_html()は、文字列をエスケープせずそのままHTMLとして出力したい場合に便利です。

# HTMLの文字列をエスケープせず生のまま扱う
raw_html("<script>alert('hi')</script>")
<script>alert('hi')</script>

# 生HTMLを子要素に含めてレンダリング
render(tags$div(raw_html("<em>already formatted</em>")))
[1] "<div><em>already formatted</em></div>"

tag() の使用例

オプション意味初期値
tag_nameHTML要素名を指定
属性(名前付き引数)と子要素(名前なし引数)を指定
tag_type要素の種類を指定:”normal”(通常の要素)または”void”(自己終了要素)のいずれか“normal”
# Webコンポーネントを作成
tag(tag_name = "calcite-action-bar", layout = "horizontal")

# 子要素を持つカスタム要素を作成
tag(
  tag_name = "my-card",
  class = "shadow",
  tag(tag_name = "my-card-header", "Title"),
  tag(tag_name = "my-card-body", "Content")
)
<my-card class="shadow">
  <my-card-header>Title</my-card-header>
  <my-card-body>Content</my-card-body>
</my-card>

# 自己終了型のカスタム要素を作成
tag(tag_name = "my-icon", name = "home", tag_type = "void")
<my-icon name="home" />

複数の要素を含むタグのリストを作成し、兄弟要素として配置する例です。

# タグリストを作成
tl <- tag_list(tags$p("one"), tags$p("two"))

# レンダリング
render(tl)
[1] "<p>one</p><p>two</p>"

doctype() の使用例

# DOCTYPE宣言とHTML構造をタグリストにまとめる
page <- tag_list(
  doctype(),
  tags$html(
    tags$head(tags$title("Home")),
    tags$body(tags$h1("Welcome"))
  )
)

# レンダリングして文字列に変換
render(page)
[1] "<!DOCTYPE html><html><head><title>Home</title></head><body><h1>Welcome</h1></body></html>"

render() の使用例

オプション意味初期値
xレンダリング対象のhypertext.tagオブジェクト、文字列、またはそれらのリストを指定
file出力先ファイルのパスを指定(省略時は文字列として返すのみでファイルには書き込まない)“”
write_modeファイルへの書き込み方法を指定:”overwrite”(上書き)または”append”(追記)のいずれか“overwrite”
# レンダリング対象のタグツリーを作成
page <- tags$html(
  tags$head(
    tags$title("Home")
  ),
  tags$body(
    tags$h1("Welcome")
  )
)

# HTML文字列として返す
render(page)
[1] "<html><head><title>Home</title></head><body><h1>Welcome</h1></body></html>"

実行例

基本的なHTMLページの作成

# HTMLドキュメントのDOCTYPE宣言を作成
doctype_html <- doctype()

# ページのタイトルを作成
title_tag <- tags$head(tags$title("サンプルページ"))
# ヘッダーを作成
header_tag <- tags$header(tags$h1("ようこそ"))

# メインコンテンツを作成
main_content <- tags$body(
  tags$p("これはサンプルページです。"),
  tags$a(href = "https://www.example.com", "リンク")
)

# 全体のHTML構造をタグリストにまとめる
html_structure <- tag_list(doctype_html, title_tag, header_tag, main_content)

# HTMLを文字列にレンダリング
rendered_html <- render(html_structure)
# 結果を表示
print(rendered_html)
[1] "<!DOCTYPE html><head><title>サンプルページ</title></head><header><h1>ようこそ</h1></header><body><p>これはサンプルページです。</p><a href=\"https://www.example.com\">リンク</a></body>"

テーブルとリストの作成

# サンプルデータを作成
data <- data.frame(
  Name = c("Alice", "Bob", "Charlie"),
  Age = c(25, 30, 35),
  stringsAsFactors = FALSE
)

# テーブルをHTMLに変換
table_html <- tags$table(
  tags$thead(tags$tr(lapply(names(data), function(x) tags$th(x)))),
  tags$tbody(lapply(1:nrow(data), function(i) {
    tags$tr(lapply(1:ncol(data), function(j) tags$td(data[i, j])))
  }))
)

# リストを作成
list_html <- tags$ul(
  lapply(1:length(data$Name), function(i) {
    tags$li(paste(data$Name[i], " - ", data$Age[i]))
  })
)

# 全体のHTML構造をタグリストにまとめる
html_structure <- tag_list(table_html, list_html)

# HTMLを文字列にレンダリング
rendered_html <- render(html_structure)

# 結果を表示
print(rendered_html)
[1] "<table><thead><tr><th>Name</th><th>Age</th></tr></thead><tbody><tr><td>Alice</td><td>25</td></tr><tr><td>Bob</td><td>30</td></tr><tr><td>Charlie</td><td>35</td></tr></tbody></table><ul><li>Alice  -  25</li><li>Bob  -  30</li><li>Charlie  -  35</li></ul>"

SVGグラフの組み込み

# サンプルデータを作成
set.seed(123)
x <- 1:10
y <- rnorm(10)

# データ点ごとに円を生成してSVGグラフを作成
svg_html <- tags$svg(
  width = 500, height = 300,
  lapply(seq_along(x), function(i) {
    tags$circle(cx = x[i] * 40, cy = (y[i] + 2) * 70, r = 5, fill = "blue")
  })
)

# 全体のHTML構造をタグリストにまとめる
html_structure <- tag_list(svg_html)

# HTMLを文字列にレンダリング
rendered_html <- render(html_structure)
# 結果を表示
print(rendered_html)
[1] "<svg width=\"500\" height=\"300\"><circle cx=\"40\" cy=\"100.766704741345\" r=\"5\" fill=\"blue\"></circle><circle cx=\"80\" cy=\"123.88757573617\" r=\"5\" fill=\"blue\"></circle><circle cx=\"120\" cy=\"249.109581990439\" r=\"5\" fill=\"blue\"></circle><circle cx=\"160\" cy=\"144.93558739972\" r=\"5\" fill=\"blue\"></circle><circle cx=\"200\" cy=\"149.050141461266\" r=\"5\" fill=\"blue\"></circle><circle cx=\"240\" cy=\"260.05454908183\" r=\"5\" fill=\"blue\"></circle><circle cx=\"280\" cy=\"172.264134419244\" r=\"5\" fill=\"blue\"></circle><circle cx=\"320\" cy=\"51.4457135775426\" r=\"5\" fill=\"blue\"></circle><circle cx=\"360\" cy=\"91.9203003674532\" r=\"5\" fill=\"blue\"></circle><circle cx=\"400\" cy=\"108.803662093003\" r=\"5\" fill=\"blue\"></circle></svg>"


この記事が誰かの役に立ちますように。

スポンサーリンク