2017-10-10 113 views
1
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?如何在索引用完时使循环不能通过NA?

回答

2

使用?lapply和简单地写

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) 
}) 
vector之前下降从 NA对象
0

您可以通过使用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") 
} 
相关问题