[R] importing many csv files into separate matrices

Greg Snow 538280 at gmail.com
Thu Dec 5 03:53:25 CET 2013


As you have noticed, using assign is not simple, and your approach has
potential to cause even more problems even if you get it working.
Here is another approach:

loadCSVfiles <- function(path) {
  x <- list.files(path, full.names=TRUE)
  out <- lapply( x, read.csv )
  names(out) <- sub(pattern="\\.csv$", replacement="", x)
  out
}

then run:

mydata <- loadCSVfiles("/my/path")

and mydata will be a list with all of your data objects with the
desired names.  You can do things like:

plot(mydata$alaska)

or

with(mydata, plot(alaska))

or

lapply( mydata, plot )

etc.

This approach does not place the individual objects into the global
workspace, but that is a good thing.

On Wed, Nov 27, 2013 at 3:39 PM, yetik serbest <yserbest at prodigy.net> 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="")))
>   }
> }
>
> 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.



-- 
Gregory (Greg) L. Snow Ph.D.
538280 at gmail.com



More information about the R-help mailing list