How to Import Data as CSV into R


There are a few different ways to import data into R. We will cover two ways in this post, downloading a file from the web and getting a file from your computer.

We will walk through downloading and importing that a CSV file from the web and then a similar CSV from our computer.

If you find CSV files online there is a very easy way to pull those files into R.

I’ll use NFL football data, but you can use anything you are interested in. NFL Savant has a wide assortment of NFL data and a few CSV files available to download. We will walk-through how to import that data from their website and import it directly into R.

If you are interested there are a bunch of CSV files here to grab.

> fileUrl <- ""
> download.file(fileUrl, destfile = "./nfl.csv")
> list.files("./")
[1] "nfl.csv"

So what happened here? First, we point to the location for R to look for the file and call that fileUrl.

Second, we use download.file to download the csv file from the URL.

Finally, list.files shows that the file was actually downloaded and is ready to use.

Now, lets look at importing a file from your desktop or folders on your computer are quite easy as well in R. We will get the working directory, I’m using a Mac, and then grab the file from that directory.

> getwd() # get your working directory
> dir.create("nfl") # create a directory
> setwd("nfl") # set the working directory
> NFLdata = read.csv("pbp-2015.csv") # file I downloaded from NFL Savant
> head(NFLdata) # see that you have data by getting a few rows

I’ve commented the code above to give you an idea of what each of these lines do. The goal is to get the directory that you want to work in, set the directory and pull the csv file into R. Then run head to just make sure you have pulled in the data and it looks correct.

There you have it, two ways to import data into R.


Please enter your comment!
Please enter your name here