如何在 R 中创建一个包含目录和子目录名称的 table?

How can I create a table with names of directories and subdirectories in R?

问题:

我想用 R 为给定路径生成 table 目录名和子目录名。

期望输出:

输出应该是 data.frame 或类似的两列,我可以用 knitr::kable 处理它以生成一个漂亮的 .htmlrmarkdown

因此结果应该大致如下所示:

|dir names            |subdir names         |
|:--------------------|:--------------------|
|                     |                     |
| DIR_1               | SUBDIR_1            |
|                     | SUBDIR_2            |
|                     | SUBDIR_3            |
| DIR_2               | SUBDIR_1            |
|                     | SUBDIR_2            |

最小示例:

这是我到目前为止的进展:

# Create directories
dir.create("DIR_1")
dir.create("DIR_2")
# Create subdirectories
dir.create("./DIR_1/SUBDIR_1")
dir.create("./DIR_1/SUBDIR_2")
dir.create("./DIR_1/SUBDIR_3")
dir.create("./DIR_2/SUBDIR_1")
dir.create("./DIR_2/SUBDIR_2")

library("knitr")
kable(list.dirs(path=".",
                recursive = TRUE, 
                full.names = FALSE),
      col.names = c("dirs & subdirs mixed"))


|dirs & subdirs mixed |
|:--------------------|
|                     |
|DIR_1                |
|DIR_1/SUBDIR_1       |
|DIR_1/SUBDIR_2       |
|DIR_1/SUBDIR_3       |
|DIR_2                |
|DIR_2/SUBDIR_1       |
|DIR_2/SUBDIR_2       |

补充问题:

如何添加第三列,其中包含存储在每个子目录中的所有文件名?

基于,以下代码生成给定目录中所有目录和文件的table:

```{r setup, echo = FALSE, results = 'hide', warning = FALSE}
library(stringr)
lapply(X = c("demo", "demo/DIR_1", "demo/DIR_2", "demo/DIR_1/SUBDIR_1", "demo/DIR_1/SUBDIR_2", "demo/DIR_1/SUBDIR_3", "demo/DIR_2/SUBDIR_1", "demo/DIR_2/SUBDIR_2"),
       FUN = dir.create)
file.create("demo/DIR_2/SUBDIR_2/file1.txt")
file.create("demo/DIR_2/SUBDIR_2/file12.txt")
```

```{r}
paths <- list.files(path = "demo/", include.dirs = TRUE, recursive = TRUE)
mytable <- str_split_fixed(paths, pattern = "/", n = str_count(paths, "/") + 1)

colnames(mytable) <- paste("Level", seq(ncol(mytable)))

knitr::kable(mytable)
```

第一个块只是创建一些演示目录和文件。实际工作由 list.filesstr_split_fixed.

完成
  • list.files returns 包含所有目录、子目录和文件的矢量,由于 include.dirs = TRUErecursive = TRUE
  • str_split_fixed/ 和 returns 处拆分 paths 矩阵。通过str_count(paths, "/") + 1动态决定分割点数

输出:

|Level 1 |Level 2  |Level 3    |
|:-------|:--------|:----------|
|DIR_1   |         |           |
|DIR_1   |SUBDIR_1 |           |
|DIR_1   |SUBDIR_2 |           |
|DIR_1   |SUBDIR_3 |           |
|DIR_2   |         |           |
|DIR_2   |SUBDIR_1 |           |
|DIR_2   |SUBDIR_2 |           |
|DIR_2   |SUBDIR_2 |file1.txt  |
|DIR_2   |SUBDIR_2 |file12.txt |