Fred Fred - 1 month ago 18
R Question

Read multiple CSV files into separate data frames

Suppose we have files file1.csv, file2.csv, ... , and file100.csv in directory C:\R\Data and we want to read them all into separate data frames (e.g. file1, file2, ... , and file100).

The reason for this is that, despite having similar names they have different file structures, so it is not that useful to have them in a list.

I could use

lapply
but that returns a single list containing 100 data frames. Instead I want these data frames in the Global Environment.

How do I read multiple files directly into the global environment? Or, alternatively, How do I unpack the contents of a list of data frames into it?

Answer

Quick draft, untested:

  1. Use list.files() aka dir() to dynamically generate your list of files.

  2. This returns a vector, just run along the vector in a for loop.

  3. Read the i-th file, then use assign() to place the content into a new variable file_i

That should do the trick for you.