【问题标题】:R: How to find/replace and then automatically execute code?R:如何查找/替换然后自动执行代码?
【发布时间】:2019-08-17 13:59:17
【问题描述】:

我有一些 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

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

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

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

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

  1. 在数据框中的“名称”列表中递归地执行此操作
  2. 每次替换后自动执行代码
  3. 并行执行每个替换和执行(运行 Windows)。

任何帮助将不胜感激

【问题讨论】:

    标签: r loops gsub


    【解决方案1】:

    如果没有完全可重复的问题,很难给出准确的答案,但这里有一个尝试。 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
    
    }
    

    【讨论】:

    • 谢谢。我将如何设置它以并行运行?
    猜你喜欢
    • 1970-01-01
    • 2019-09-20
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多