0

I have a little problem with my loop in R. The idea is that I have 1000 files from queryCM_20131215.LST, queryCM_20131216.LST, ... queryCM_20170118.LST ; I want to extract the date for each file. But my result gives me only the last one. Is there a way out ? here is my code :

listLST <- dir(path = "C:/Users/BQKJ3140/Desktop/DOCS/base/histo/",pattern = "*.LST")

for (k in 1:length(listLST)){ 
file_name[[k]] <- listLST[[k]]

file_date[[k]]<- as.Date(strsplit(file_name[[k]],"_")[[1]][2], "%Y%m%d") }

  • I have a few idea's, however it is good to show us a reproducible [example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), use code indentations in your question and if you are using any libraries mention those too. I have no clue how a `*.LST` file should look like, so if you could show the first few lines that would be great. – Erik Schutte May 12 '17 at 09:00
  • `dt <- as.Date(gsub("\\w+_(\\d{8})\\.LST","\\1",listLST),"%Y%m%d")` – PKumar May 12 '17 at 09:26
  • @PKr , i extract the date for a file easily. I want now a loop for the 1000 files. the final result shows me only the date of the 100th file. – Taofik Lawal May 12 '17 at 09:30
  • initilaize the file_date as list, something like : `file_data <- list()`, this should be outside the loop then remove the first line in for loop( I am not sure why you are using it) then use `file_date[i] <- as.Date .....` whatever you are trying to use. but what did you get when you ran the earlier comment of mine? – PKumar May 12 '17 at 09:36
  • @PKr thanks very much, it works now by following your first idea and the last one as ' file_data <- list()' out of the loop. – Taofik Lawal May 12 '17 at 09:50

1 Answers1

0

Here is also you can do..

listLST <- dir(path = "C:/Users/BQKJ3140/Desktop/DOCS/base/histo/",pattern = "*.LST")
readDate <- sapply(strsplit(listLST,"[_.]"),function(x){x[2]})
readDate <- as.Date(readDate,"%Y%m%d")
Anish
  • 114
  • 1
  • 2
  • 10