Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading csv files in a for loop and assigning dataframe names [duplicate]

Tags:

for-loop

r

Possible Duplicate:
Read multiple CSV files into separate data frames

I need to read many csv files into dataframes from one folder. The csv file names are of the form fxpair-yyyy-mm.csv (e.g. AUDJPY-2009-05.csv). I want to read all csv files in and create dataframes of the form fxpair.yyyy.mm

I am having trouble creating the dataframe names in the loop for assignment from the read.csv statements

filenames <- list.files(path=getwd())  
numfiles <- length(filenames)  

#fx.data.frames to hold names that will be assigned to csv files in csv.read
fx.data.frames <- gsub(pattern="-",x=filenames,replacement=".")  
fx.data.frames <- gsub(pattern=".csv",x=fx.data.frames,replacement="")

i <-1  
for (i in c(1:numfiles)){  
   filenames[i] <- paste(".\\",filenames[i],sep="")  
   fx.data.frames[i] <- read.csv(filenames[i], header=FALSE)
}

The csv.read seems to work fine but I am not able to create the dataframe objects in the way I intend. I just want some way to name the dataframes read in the fxpair.yyyy.mm format based on the file name.

Am I missing something obvius? THANK YOU FOR ANY HELP!!

like image 251
user674042 Avatar asked Dec 16 '22 16:12

user674042


2 Answers

Just to illustrate my comment :

for (i in filenames){  
   name <- gsub("-",".",i)
   name <- gsub(".csv","",name)  
   i <- paste(".\\",i,sep="")
   assign(name,read.csv(i, header=FALSE)
}

Or, to save all dataframes in a list :

All <- lapply(filenames,function(i){
    i <- paste(".\\",i,sep="")
    read.csv(i, header=FALSE)
})
filenames <- gsub("-",".",filenames)
names(All) <- gsub(".csv","",filenames)

I'd go for the second solution, as I like working with lists. It's less of a hassle to clean up the workspace afterwards. You also get rid of the name and i clutter in the global environment. These might cause some funny bugs later in the code if you're not careful. See also Is R's apply family more than syntactic sugar?

like image 196
Joris Meys Avatar answered Jan 31 '23 10:01

Joris Meys


How about this :

for (i in c(1:numfiles)){  
    filenames[i] <- paste(".\\",filenames[i],sep="")  
    assign(gsub("[.]csv$","",filenames[i]),read.csv(filenames[i], header=FALSE))
}
like image 35
Matt Dowle Avatar answered Jan 31 '23 10:01

Matt Dowle