2017-10-10 69 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") 
} 
相關問題