Chapter 11 Import & Export

It is important to be able to load data to R and to save any output you might need. R offers easy ways to do so, which we will introduce in this chapter.

But before doing so, we will need to talk briefly about the concept of working directories. Just as when working on the command line, R has a working directory in which, well, you work! Specifically, the working directory is the default place in your file system at which R looks for files you want to load and where it stores files you write.

You can find out your current working directory with the function getwd(). Note that your working directory might be different from mine.

> getwd()
[1] "/Users/xenia/git/runifr"

You can also easily change your working directory by using the function setwd() and providing either the full or relative path. Note again that different filesystems differ in how they are organized, and hence they offer different options.

On a Unix system (e.g. Linux and OS X), this should work

> getwd() # were I am now
[1] "/Users/xenia/git/runifr"
> a <- getwd() # storing where I am now
> setwd("~/") # changing to home folder
> getwd()
[1] "/Users/xenia"
> setwd(a) # changing back to original
> getwd()
[1] "/Users/xenia/git/runifr"

If you are on a Windows computer, relative paths will work the same, but your full path will start with the drive letter, i.e. “C:” or “D:”.

Rather than through the console, you can also change the working directory via RStudio under Session -> Set Working Directory, where you can either choose directly by browsing or switch to the directory of the current R script.

11.0.1 Exercises: Data Input and Export

See Section 18.0.26 for solutions.

  1. What is your current working directory?

  2. Create a directory of your choice somewhere, then switch your working directory there. Did it work?