Pages

Tuesday, May 11, 2010

Reading in data in R

Reading in data can be a chore in R if you haven't done it before. In this post, I describe how to read data into R's most common data object -- the data frame.

## ----------------------------------------------------#### The most basic structure in R is a data frame. The #### goal here is to read data from some external source #### into an R data frame #### ----------------------------------------------------##

## --------------------------------------------------- #### The standard space-delmited function is read.table()#### #### To read in the data, you will want to save the file #### to a known directory. For me, this is "C:/R/" #### #### Time saving note: these commands sometimes require #### double backspaces in the file path. So, even if I #### saved my file at "C:/R/data.txt" I tend to type #### "C://R//data.txt" #### --------------------------------------------------- ##

## --------------------------------------------------- #### A common difficulty is that the basic command does #### not read in Excel Workbook files. For this, there #### are a couple of workarounds. My favorite is to #### use read.csv(). #### --------------------------------------------------- ##

## First, save your Excel file as type "csv"## Second, use a command like the following:

insulin.df = read.csv("C://R//insulin.csv", header = T)

##----------------------------------------------------#### Suppose you want to read in an Stata .dta file #### The command is read.dta(). #### #### This requires loading a package. #### In this case, the "foreign" library. #### #### Because external packages are not part of the base #### group of packages, you'll have to tell R to use #### them with the command library() ####----------------------------------------------------##

library(foreign)

caschool.df = read.dta("C://R//caschool.dta")

------------------------------------------------------

If you came across this page looking for advice on how to read data into R, you likely have a data set that you want to use. If you want to use some of the data referenced in this post, the traffic data set is here (just copy and paste into Notepad, and save to your favorite directory):