Using paste( ) to read and write multiple files in R

This post is a quick tip on how to use the paste( ) function to read and write multiple files. First, let’s create some data.

The next step is not necessary, but makes the subsequent code more readable.

The following example is silly because you would rarely want to split your data as shown in this example, but (hopefully) it clearly illustrates the general idea of using paste( ) to create dynamic file names when writing files.

The result of this loop is four CSV files: HighFemale.csv, HighMale.csv, LowFemale.csv, and LowMale.csv.

We can use the same basic idea to read those same four files into a single data frame. The key is to initialize an empty data frame and then append, via rbind( ), the data from each of the four files.

I found this approach useful when I used a supercomputer to conduct many, many runs of an agent-based model. My jobs were queued more quickly on the supercomputer if they were small, so I broke my simulation experiments into many small jobs. This produced many files that I needed to combine into one data frame for analysis in R.

The following two tabs change content below.

Latest posts by Travis Hinkelman (see all)

3 thoughts on “Using paste( ) to read and write multiple files in R

  1. Jonathan Moscovici

    FInally! I’ve asking around for an easy way to accomplish this for a while now in R. I’m glad I stumbled on your post. Now, how to do it in SAS… 😉


Leave a Reply