当索引用完时,如何使for循环不超过NA


xlen <- 50                                          # Length
xGRU <- seq(1, 2723, by = xlen)                     # Start ID
xjob <- 36                                          # Numbe of Jobs per Joblist
# List of all run Commands
runcommands <- paste("TESTTHIS", xGRU, xlen , '-r d', '-m', sep=" ")
runcommands <- append(head(runcommands, -1),
                           paste("TESTTHIS", tail(xGRU,1), 11723%%xlen ,
                                 '-r d', '-m', sep=" "))
for(i in seq(1, length(runcommands), by = xjob)){
  jobfileName <- paste0('data_raw/joblist_', i, ".txt")
  cat(paste(runcommands[i:(i+xjob-1)]), file=jobfileName, append=TRUE, sep = "n")
}

但是创建的最后一个文件包含NAs。如何确保for loop在索引用完时不会写出 NA?

使用?lapply,只需在写入之前从每个vector中删除NA对象

lapply(seq_along(runcommands), function(i){
    # create a new file inside of the temporary directory
    # for help see ?sprintf
    fl <- sprintf('data_raw/joblist_%s.txt', i)
    # cleaned up your seq chunk a bit, and then the key is to remove
    # the NA items prior to writing to file
    job_list <- runcommands[seq(i, i + (xjob - 1))] %>% .[!is.na(.)]
    stringi::stri_write_lines(job_list, sep = "n", fname = fl)
})

您可以通过在cat函数调用中使用更严格的方式来防止这种情况发生。但作为快速解决方法,您可以这样做:

for(i in seq(1, length(runcommands), by = xjob)){
  jobfileName <- paste0('~/SO_posts/joblist_', i, ".txt")
  cat(paste(na.omit(runcommands[i:(i+xjob-1)])), file=jobfileName, append=TRUE, sep = "n")
}

最新更新