【发布时间】:2015-09-18 11:53:47
【问题描述】:
我想从我的 R 源脚本中提取 cmets(与模式匹配),以保留它们出现的函数。
目标是使用经典的降价复选框 - [ ] 或 - [x] 在函数体代码中编写文档 cmets,然后提取这些 cmets 以作为字符向量列表进行进一步处理 - 我可以轻松地将其写入新的 .md 文件。
下面的可重现示例和预期输出。
# preview the 'data'
script_body = c('# some init comment - not matching pattern','g = function(){','# - [x] comment_g1','# - [ ] comment_g2','1','}','f = function(){','# - [ ] comment_f1','# another non match to pattern','g()+1','}')
cat(script_body, sep = "\n")
# # some init comment - not matching pattern
# g = function(){
# # - [x] comment_g1
# # - [ ] comment_g2
# 1
# }
# f = function(){
# # - [ ] comment_f1
# # another non match to pattern
# g()+1
# }
# populate R souce file
writeLines(script_body, "test.R")
# test it
source("test.R")
f()
# [1] 2
# expected output
r = magic_function_get_comments("test.R", starts.with = c(" - [x] "," - [ ] "))
# r = list("g" = c(" - [x] comment_g1"," - [ ] comment_g2"), "f" = " - [ ] comment_f1")
str(r)
# List of 2
# $ g: chr [1:2] " - [x] comment_g1" " - [ ] comment_g2"
# $ f: chr " - [ ] comment_f1"
【问题讨论】: