Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop with file names in R

Tags:

loops

r

filenames

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.

like image 939
dede Avatar asked Oct 17 '25 13:10

dede


1 Answers

Drop the extension "csv", then add "Rdata", and use filenames in the loop, for example:

myFiles <- list.files(pattern = "\\.csv$") 

for(i in myFiles){
  myDf <- read.csv(i)
  outputFile <- paste0(tools::file_path_sans_ext(i), ".Rdata")
  outputFile <- gsub("nE_pT_", "e_", outputFile, fixed = TRUE)
  save(myDf, file = outputFile)
}

Note: I changed your variable names, try to avoid using function names as a variable name.

like image 149
zx8754 Avatar answered Oct 19 '25 02:10

zx8754