[R] importing many csv files into separate matrices

David Winsemius dwinsemius at comcast.net
Thu Nov 28 21:28:35 CET 2013


On Nov 27, 2013, at 2:39 PM, yetik serbest wrote:

> 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="")))
>   }
> }

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
  }
}



>  
> Instead, if I execute the foor loop in the command line, it works. I am puzzled. Appreciate any help.
>  
> thanks
> yetik
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list