How to build a dendrogram from a directory tree?

后端 未结 3 565
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 18:05

Given a root absolute directory path. How do I generate a dendrogram object of all path\'s below it so that I can visualize the directory tree with R?

Suppose the fo

3条回答
  •  感情败类
    2020-12-23 18:18

    It's worth adding that excellent fs package offers dir_tree function that delivers this functionality to R in a very convenient manner.

    tmp_dir <- tempdir()
    # Create some directories
    for (i in 1:10) {
        dir.create(path = file.path(tmp_dir,
                                    basename(tempfile(pattern = "dir")),
                                    basename(tempfile(pattern = "sub_dir"))),
                   recursive = TRUE)
    }
    # Create directory tree
    fs::dir_tree(path = tmp_dir, recurse = TRUE)
    

    Results

    /tmp/RtmpEhB0ne
    ├── dir15213121dd5903
    │   └── sub_dir1521315a5425ba
    ├── dir152131227b086f
    │   └── sub_dir1521314255d96b
    ├── dir152131353e6603
    │   └── sub_dir1521315b52aeed
    ├── dir15213136870535
    │   └── sub_dir15213127b34f64
    ├── dir1521313bbf738b
    │   └── sub_dir152131473939ea
    ├── dir152131403f4fd5
    │   └── sub_dir152131115296e7
    ├── dir152131503d0d55
    │   └── sub_dir15213114368572
    ├── dir1521316f0bb0c3
    │   └── sub_dir1521314aea266b
    ├── dir1521317fe305e9
    │   └── sub_dir152131bcfe8a
    └── dir1521319800dfb
        └── sub_dir15213129defd4a
    

    In addition to printing directory tree, discovered paths can be returned to an object.

    sink(file = tempfile(fileext = ".log"))
    res_fs_tree <- fs::dir_tree(path = tmp_dir, recurse = TRUE)
    sink()
    res_fs_tree[[1]]
    # [1] "/tmp/RtmpEhB0ne/dir15213121dd5903/sub_dir1521315a5425ba"
    

提交回复
热议问题