0

我有一个文本文件,其中有 2 个参数 - 开始时间和结束时间。我创建了 2 个不同时间的向量。我想要

  1. 用这些时间替换开始时间/结束时间
  2. 为每个组合写出不同的文本文件(在本例中为 3 个)

    runStart <- lubridate::ymd_hm('2016-01-01 00:00') #Start of the entire run
    st <- runStart + months(0:2) #Start times
    et <- runStart + months(1:3) - lubridate::dhours(1) #End times
    
    mult_one<-function(st,et){
    readLines("template.txt") %>%
    gsub(pattern = "starttime", replace = st) %>%
    gsub(pattern = "endtime", replace = et)
    }
    
    x <- mapply(mult_one,st,et)
    write.table(x[,1],'template_1.txt', row.names = F, col.names = F)
    

这给了我想要的输出。

但我想写出函数内的文件。最好template_1.txt, template_2.txt, template_3.txt自动使用 as 文件名。我怎样才能做到这一点?

dput(readLines("template.txt"))

这里:

  c("", "\"! ***********************************************************************************************************************\"", 
"\"simulStart              starttime     ! (01) simulation start time -- must be in single quotes\"", 
"\"simulFinsh              endtime      ! (02) simulation end time -- must be in single quotes\"", 
"\"\"", "\"! ***********************************************************************************************************************\""
)
4

1 回答 1

0

根据您问题中的信息,如果我理解清楚,您想在函数中编写 3 个文件。你可以这样做:

# Adding num_of_files as a third argument in your function. 
mult_one<-function(st,et,num_of_files){
   for (i in 1:num_of_files) {
      readLines("template.txt") %>%
      gsub(pattern = "starttime", replace = st) %>%
      gsub(pattern = "endtime", replace = et)
      write.table(.,paste("template_", num_of_files, ".txt",sep=""),row.names=FALSE,col.names=FALSE)
   }
}

## Then you just call the function in mapply with 3 arguments
x <- mapply(mult_one,st,et,num_of_files)

注意:由于我没有测试数据,因此没有测试代码。但是,我希望这对你有所帮助。

于 2017-09-19T22:46:17.607 回答