1

I am new to R and trying to use file names as variable names in R.

Basically, I have a folder containing a list of files and I want to load all files into R and use their names for variable names

for(i in list.files()) {
  loaddata(i,i)
}

This does not work, I also tried as.name and paste, both don't work. Can anyone please help?

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
user2324644
  • 43
  • 2
  • 11

1 Answers1

0

Here's a one liner that'll get you most of the way:

sapply(list.files("~/r"), FUN = function(X) assign(X, rnorm(1))) 

This assigns a random number to an object in the global environment, with each object taking its name from the files in my ~/r/ directory.

To give a concrete example, say we had a directory ~/r and we wished to read the files in and have them as seperate items in the environment -- then one would do the following:

list2env(sapply(list.files("~/r"), FUN = function(X) read.csv(X)), globalenv())

This is a combination of two commands that has the advantage of not cluttering the global environment with the list containing all the files.

In steps we would do:

inList <- sapply(list.files("~/r"), FUN = function(X) read.csv(X))
list2env(inList, globalenv())
ricardo
  • 8,195
  • 7
  • 47
  • 69
  • i tried this, it does not load any variable only display file names along with random numbers, any modification? – user2324644 Jul 22 '13 at 17:08
  • i mean the command only gives result on console, but nothing is loaded into R – user2324644 Jul 22 '13 at 18:12
  • @user2324644 i edited the answer to give you a full example. note that i've restricted the case to `.csv` files, but it should be obvious with a moments effort how to generalise it to whatever case you have. – ricardo Jul 22 '13 at 20:56