4
4

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.

R でランダムに木を生成する #rstatsj

Last updated at Posted at 2016-01-18

R で適当な木を生成する必要があったので適当に書きました。

R
generate_tree <- function(parent_id, max_width, max_depth) {
  sibling_num <- min(sample(seq_len(max_width), 1), 9)
  depth_num <- sample(seq_len(max_depth)-1, sibling_num, replace = TRUE)
  child_ids <- paste0(parent_id, seq_len(sibling_num))
  result <- data.frame(parent=parent_id, child=child_ids, stringsAsFactors = FALSE)
  for(i in seq_len(sibling_num)) {
    if(depth_num[i] != 0) {
      child_tree <- generate_tree(child_ids[i], max_width, max_depth-1)
      result <- rbind(result, child_tree)
    }
  }
  result
}

使い方:

R
generate_tree(1, max_width = 3, max_depth = 3)
結果
  parent child
1      1    11
2      1    12
3      1    13
4     12   121
5    121  1211
6    121  1212
7    121  1213
8     13   131

適当な木のエッジ情報を生成します。

分かりにくいので igraph で描画する。

R
library(igraph)
plot_igraph <- function(igraph) {
  plot.igraph(igraph,
              layout=layout_as_tree,
              vertex.size=20,
              vertex.label.cex=0.8,
              vertex.label = V(igraph),
              edge.arrow.size = 0.5)
}
R
tr <- generate_tree(1, 3, 3)
g <- graph.data.frame(tr)
plot_igraph(g)

Rplot.png

R
tr <- generate_tree(1, 4, 4)
g <- graph.data.frame(tr)
plot_igraph(g)

Rplot03.png

Enjoy!

追記

かずたん先生に教えてもらった DiagrammeR で描いてみました。

R
library(DiagrammeR)

edges <- generate_tree(1, 3, 3)
edges_df <- create_edges(from = edges$parent,
                         to = edges$child)
graph <- create_graph(edges_df = edges_df)

render_graph(graph)

Rplot04.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?