Skip to content

importing many csv files into separate matrices

2 messages · yetik serbest, David Winsemius

#
Hi Everyone,
?
I am trying to import many CSV files to their own matrices. Example, alaska_93.csv to alaska. When I execute the following, for each csv.file separately it is successful.
?
singleCSVFile2Matrix <- function(x,path) {
?assign(gsub(pattern=".csv",x,replacement=""),read.csv(paste(path,x,sep="")))
}
?
when I try to include it in a loop in another function (I have so many csv files to import), it doesn't work. I mean the following function doesn't do it.
?
loadCSVFiles_old <- function(path) {
?x <- list.files(path)
?for (i in 1:length(x)) {
??assign(gsub(pattern=".csv",x[i],replacement=""),read.csv(paste(path,x[i],sep="")))
??}
}
?
Instead, if I execute the foor loop in the command line, it works. I am puzzled. Appreciate any help.
?
thanks
yetik
#
On Nov 27, 2013, at 2:39 PM, yetik serbest wrote:

            
It appears you are not returning the values that you created inside that function to the global environment. I would have expected that you would either given `assign` an environment argument or that you would have created a list of items to return from the function.

?environment
?assign

Perhaps:

loadCSVFiles_old <- function(path) {
 x <- list.files(path)
 for (i in 1:length(x)) {
  assign(gsub(pattern=".csv",x[i],replacement=""),
         read.csv(paste(path,x[i],sep="")))
         envir=.GlobalEnv
  }
}
David Winsemius
Alameda, CA, USA