我在 R 中有很多不同的脚本,它们通过 source()
相互获取。我正在寻找一种创建概览图的方法,该图可以直观地链接每个脚本,以便我可以轻松查看代码的“源层次结构”。
结果可能类似于:
我希望有一个不需要软件许可证的解决方案。
希望它有意义! :)
答案 0 :(得分:1)
我可以建议您使用 Knime。它有你正在寻找的那种图表。它已经编写了一些脚本来清理、可视化数据和写入输出,并与 R 和 Python 集成。
https://docs.knime.com/?category=integrations&release=2019-12 https://www.knime.com/
祝你好运。
答案 1 :(得分:0)
出于示例目的,将目录更改为空目录并运行最后注释中的代码以创建一些示例 .R 文件。
在下面代码的前两行中,我们将 files
变量设置为包含感兴趣的 R 文件路径的字符向量。我们还将 st
设置为主源文件的路径。这里是 a.R
,但可以适当更改。
代码首先在每个此类文件的开头插入包含在变量 insert
中的行。
然后它使用显示的 source
命令检测 trace
,以便每次运行 source
时都会生成一条日志记录。然后我们source
顶级 R 文件。
最后我们读入日志并使用 igraph 包生成源文件树。 (可以使用任何其他可以生成合适图形的包。)
# change the next two lines of code appropriately.
# Settings shown are for the files generated in the Note at the end
# assuming they are in the current directory and no other R files are.
files <- Sys.glob("*.R")
st <- "a.R"
# inserts indicated line at top of each file unless already inserted
insert <- "this.file <- normalizePath(sys.frames()[[1]]$ofile)"
for(f in files)
inp <- readLines(f)
ok <- !any(grepl(insert, inp, fixed = TRUE)) # TRUE if insert not in f
if (ok) writeLines(c(insert, input), f)
}
# instrument source and run to produce log file
if (file.exists("log")) file.remove("log")
this.file <- "root"
trace(source, quote(cat("parent:", basename(this.file),
"file:", file, "\n", file = "log", append = TRUE)))
source(st) # assuming a.R is the top level program
untrace(source)
# read log and display graph
DF <- read.table("log")[c(2, 4)]
library(igraph)
g <- graph.data.frame(DF)
plot(g, layout = layout_as_tree(g))
例如,如果我们在最后的 Note 中生成了文件,那么上面的代码会生成此图:
cat('
source("b.R")
source("c.R")
', file = "a.R")
cat("\n", file = "b.R")
cat("\n", file = "C.R")