For loop with file names in R

Viewed 10102

I have a list of files like:

nE_pT_sbj01_e2_2.csv, nE_pT_sbj02_e2_2.csv, nE_pT_sbj04_e2_2.csv, nE_pT_sbj05_e2_2.csv, nE_pT_sbj09_e2_2.csv, nE_pT_sbj10_e2_2.csv

As you can see, the name of the files is the same with the exception of 'sbj' (the number of the subject) which is not consecutive.

I need to run a for loop, but I would like to retain the original number of the subject. How to do this? I assume I need to replace length(file) with something that keeps the original number of the subject, but not sure how to do it.

setwd("/path")

file = list.files(pattern="\\.csv$") 
for(i in 1:length(file)){
  data=read.table(file[i],header=TRUE,sep=",",row.names=NULL)
  source("functionE.R")
  Output = paste("e_sbj", i, "_e2.Rdata")
  save.image(Output)
}

The code above gives me as output:

e_sbj1_e2.Rdata,e_sbj2_e2.Rdata,e_sbj3_e2.Rdata, e_sbj4_e2.Rdata,e_sbj5_e2.Rdata,e_sbj6_e2.Rdata.

Instead, I would like to obtain:

e_sbj01_e2.Rdata,e_sbj02_e2.Rdata,e_sbj04_e2.Rdata, e_sbj05_e2.Rdata,e_sbj09_e2.Rdata,e_sbj10_e2.Rdata.

3 Answers
Related