Programming with R

The best way to learn how to program is to do something useful, so this introduction to R is built around a common scientific task: data analysis.

Our real goal isn’t to teach you R, but to teach you the basic concepts that all programming depends on. We use R in our lessons because:

  1. we have to use something for examples;
  2. it’s free, well-documented, and runs almost everywhere;
  3. it has a large (and growing) user base among scientists; and
  4. it has a large library of external packages available for performing diverse tasks.

But the two most important things are to use whatever language your colleagues are using, so you can share your work with them easily, and to use that language well.

We are studying inflammation in patients who have been given a new treatment for arthritis, and need to analyze the first dozen data sets of their daily inflammation. The data sets are stored in comma-separated values (CSV) format: each row holds information for a single patient, and the columns represent successive days. The first few rows of our first file look like this:


We want to:

  • load that data into memory,
  • calculate the average inflammation per day across all patients, and
  • plot the result.

To do all that, we’ll have to learn a little bit about programming.


Learners need to understand the concepts of files and directories (including the working directory). We often use RStudio to teach this lesson, but it is not required.

Getting ready

You need to download some files to follow this lesson:

  1. Make a new folder in your Desktop called r-novice-inflammation.
  2. Download and move the file to this folder.
  3. If it’s not unzipped yet, double-click on it to unzip it. You should end up with a new folder called data.
  4. You can access this folder from the Unix shell with:

    $ cd && cd Desktop/r-novice-inflammation/data


  1. Analyzing patient data
  2. Creating functions
  3. Analyzing multiple data sets
  4. Making choices
  5. Command-Line Programs
  6. Best practices for using R and designing programs
  7. Dynamic reports with knitr
  8. Making packages in R

Other Resources

Supplemental lessons