R:如何查找/替换然后自动执行代码?



>我在一个文件(test_code中保存了一些R代码。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

我想用数据帧中的每个"名称"替换代码中的单词(示例代码中的"ABC"(。例如,将"name1"替换为"ABC"。然后,自动执行代码。然后,并行地将"name2"替换为"ABC",然后自动执行代码。依此类推,在数据帧中的"名称"列表中向下。

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

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

但是,我不确定如何进行:

  1. 归地在数据帧中的"名称"列表中执行此操作
  2. 每次替换后自动执行代码
  3. 并行执行每个替换和执行(运行 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
}

最新更新