Previous: Loading Data Up: Loading Data Next: Special Cases When Loading

Standard Ways to Load Data

Make sure that the data file is saved in your working directory. You can check to see what your working directory is by starting R, and typing getwd(). If you wish to use a different directory as your starting directory, use setwd("dirpath"), where "dirpath" is the full directory path of the directory you would like to use as your working directory.

After setting your working directory, load data using one of the following methods:

  1. If your dataset is in a tab- or space-delimited .txt file, use read.table("mydata.txt")
  2. If your dataset is a comma separated table, use read.csv("mydata.csv").
  3. To import SPSS, Stata, and other data files, use the foreign package, which automatically preserves field characteristics for each variable. Thus, variables classed as dates in Stata are automatically translated into values in the date class for R. For example:
    > library(foreign)                           # Load the foreign package.  
    > stata.data <- read.dta("mydata.dta")       # For Stata data.
    > spss.data <- read.spss("mydata.sav", to.data.frame = TRUE) # For SPSS.
    
  4. To load data in R format, use load("mydata.RData").
  5. For sample data sets included with R packages such as Zelig, you may use the data() command, which is a shortcut for loading data from the sample data directories. Because the locations of these directories vary by installation, it is extremely difficult to locate sample data sets and use one of the three preceding methods; data() searches all of the currently used packages and loads sample data automatically. For example:
    > library(Zelig)                              # Loads the Zelig library. 
    > data(turnout)                               # Loads the turnout data.
    



Gary King 2011-11-29