R:如何find/replace然后自动执行代码?

R: How to find/replace and then automatically execute code?

我在文件中保存了一些 R 代码 (test_code.R)。

ABC_common <- big_fread1("E:/folder/ABC_annotation.text", 
every_nlines=5e5,sep="\t")

makeGRangesFromDataFrame(ABC_common,seqinfo=NULL)

ABC_shared <- ABC_unique[!rownames(ABC_unique) %in% CBL_shared$column1,]

我还有一个名字数据框

goal_shared <- read.delim("E:/goal_shared.txt", header=FALSE)

     V1
1    name1
2    name2
3    name3
4    name4

我想用数据框中的每个 "name" 替换代码中的一个词(示例代码中的 "ABC" )。例如,将 "name1" 替换为 "ABC"。然后,自动执行代码。然后,并行地,将"name2"替换为"ABC",然后自动执行代码。以此类推,在数据框中向下 "names" 的列表。

到目前为止,我已经使用gsub_file成功地将"ABC"替换为"name1"。

gsub_file("test_code.R", "ABC", "name1", fixed=TRUE)

但是,我不确定如何继续:

  1. 在数据帧
  2. 的"names"列表中递归执行此操作
  3. 每次替换后自动执行代码
  4. 并行执行每个替换和执行 (运行 Windows)。

如有任何帮助,我们将不胜感激

如果没有完全可重现的问题,很难给出准确的答案,但这是一次尝试。 gsub_file 就地更改了目标文件,因此在您编写的代码中,替换只会起作用一次。更好的解决方案是将模板文件复制到临时连接中,然后修改它:

for (i in goal_shared$V1) {

  f <- tempfile() # create a temp file
  template <- readLines('test_code.R') # read your template file
  writeLines(template, f) # write the template code into a temp connection
  gsub_file(f, "ABC", i, fixed=TRUE) # rewrite the temp file
  source(f) # run the temp file

}