1.1 Intro to R: Installation, Working Directories, & Packages
Objective
The purpose of this exercise is to get R or RStudio (preferred) installed on your computer, set your working directory, check out some basic concepts with a quick "Hello World!" exercise, and practice loading in a new package. By the end of this exercise, you’ll have gained a rudimentary understanding of R and its potential.
Background
The R statistical software is a tool for analyzing and visualizing data. It was designed in 1993 as a prototype to see how a statistical computing platform might be built. Today, R has become more than just a simple testbed. It's a widely used, collaborative, open source environment for statistical modeling and data analysis.
The R programming language is based on the S language (a statistical language based around functions and the concept of objects). R is an interpreted language, which means that it interprets plain text and numerical values input by the user. For example, if you type in 2+2 at the caret prompt in the R console, the interactive R session will reply with 4. It's a calculator! The fact that R is an interpreted language makes coding at the command prompt very approachable; whatever you type in, you can see the results immediately when you press the Enter key. R handles all sorts of things, from classical statistical tests to data cleansing and advanced analysis. If you have some data and want to do something with it, R more than likely has a solution for you.
Part 1A: Installing R (go to Part 1B to install RStudio):
Go to the website http://www.r-project.org/. This is the home base for everything base R, including manuals, FAQs, screenshots, and code repositories.
On the left-hand side of your screen, click on "CRAN". This will take you to a page titled "CRAN Mirrors".
On the page "CRAN Mirrors", scroll down until you find a link that's close to you geographically: this will take you to a page called The Comprehensive R Archive Network (that's what CRAN stands for).
On that page, click the link that matches your operating system. This will take you to a page titled "R for (your operating system)".
There, do one of the following:
- For Mac OS: click on "Download R for Mac OS". After that, select the link that ends in the file format ".pkg".
- Note: If your browser informs you that this file may harm your computer, select "keep".
- For Windows: click on "Download R for Windows". After that, click on the link titled "base". Then, click "Download R for Windows".
- Note: If your browser informs you that this file may harm your computer, select "keep".
- Once the download is complete, go to your operating system’s Downloads folder. Double click the file/package and follow the on-screen instructions to install R. A shortcut for R should be created on your desktop if you are running Windows, or your applications folder if you are running Mac OS.
Part 1B: RStudio (optional if you just installed base R):
Go to the website https://www.rstudio.com/products/rstudio/download/. Click on the green download button under the green word FREE.
In the Installers section, click on the link that corresponds to your operating system
After the download completes, run the file and follow the prompts.
Part 2: Getting and Setting Your Working Directory
Now that you have R installed on your computer, you can set your working directory. This is the place R will look to find data, functions, and other resources on your computer. You can change your working directory to point R to any location on your local machine, depending on which local directory contains the data, functions, or other files you want to import.
Open up R by clicking on the Icon that was created for you in Part 1. An R coding environment should pop up. You'll see some introductory text and a caret (">") which is R's way of telling you it's ready to do your bidding.
The first thing we want to do is find out where the working directory is already set. You want to set it to a place that's convenient for you. To get your current directory, type getwd() and press Enter.
Your working directory will display below where you typed getwd(). I recommend creating a folder titled R in the default working directory (you'll do this outside of R, either in the "Finder" application on Macs, or through the "Computer" option that you see when you click the Windows start button). Navigate to it by typing
setwd("/your/directory/name/goes/here/R")If you wish to change your working directory entirely, find a directory that you like and use setwd to specify the path to that directory.
If all is successful with the step above and you type getwd() once again, you should see the directory you just specified. Your working directory has now been set!
Double check by typing dir() -- after which you should see the contents of the directory you'd like R to point to.
Part 3: A Very, Very Simple Hello World! Exercise
Now that your working directory is set, let’s do a simple "Hello World!" Exercise to become more familiar with R syntax. You will use the R console to do this… that’s the window that has the caret prompt in it (lower left panel in RStudio).
In your R console, type x <- ("Hello")and press Enter. This assigns the word Hello to a variable x by using the assignment operator <- which looks like a left-pointing arrow (or a less-than sign eating a dash). Note that any string, made of characters containing non-numeric values, must be contained in quotes.
Type x and press Enter - you should see [1] "Hello"
Once again in your console, type y <- ("World!") and press Enter
Type y and you should see [1] "World!". This time, we assigned the word World! to a variable named y.
Use paste to combine these two words and press enter:
paste(x,y)You will see [1] "Hello World!" displayed. The paste command combined the contents of the variables x and y that you defined previously.
Now write a function to print "Hello World!":
- Call the function by typing hello() and pressing Enter. What do you see? Try it again with just hello – leave off the parenthesis. What happens? Remember to include the parenthesis whenever you call a function, or you’ll get an error like this.
Part 4: Installing Packages (Using tidyverse as an Example)
One of the best things about R is that it’s a highly versatile environment. It allows you to download packages to do all sorts of stuff like create awesome graphs, tables, and maps, and it can also help you mine and analyze data. Bringing new packages into your R environment is something you will do often. This is a three-step process. First, figure out which R package will provide the functionality that you need. Maybe you see a great package in a Stack Overflow answer, and you know you want it. Or, you type "package to draw topo maps in R" into Google (or whatever task you need to accomplish). A search might produce many R packages that provide similar functionality, so you'll have to install the one that looks best; try it out to see if it's what you're looking for. The worst that can happen is – you don’t like it, so you remove it and try a new one.
Let's say we know that the tidyverse package is something everyone needs, and we don’t have it yet. The second step in the three-step process is to install this package (that is, download the code to our machine) from a CRAN mirror (one of the many repositories around the world that provide us with an up-to-date collection of all of the publicly downloadable R packages).
To get the package, type this on the R command line, replacing package_name with the actual name of the package you want to retrieve – in this case, tidyverse (be VERY CAREFUL to get the capitalization and spacing right, and yes, the package name must be in quotes):
install.packages("package_name")(We didn’t type it for you in the line of code to see if you are paying attention and following instructions.) OK! If everything went well, you should see something like this:
The downloaded binary packages are in
C:\Users\User\AppData\Local\Temp\RtmpCmSbyi\downloaded_packages
If you are given the option to "Install Dependencies" at any time – JUST DO IT. It will save you A LOT of hassle later. This will download your selected library. To load the library that you just downloaded into active memory so you can use it, type:
This will make it possible for you to use the library you have installed. Now that you have the package installed on your local machine, you’ll never have to install it again (unless it gets corrupted, or you change versions). However, every time you launch the R environment, you'll have to use the library command for each package that you want to use during that session.
v ggplot2 3.0.0 v purrr 0.2.5
v tibble 1.4.2 v dplyr 0.7.7
v tidyr 0.8.0 v stringr 1.3.0
v readr 1.1.1 v forcats 0.3.0
-- Conflicts ------------------------------ tidyverse_conflicts() --
x dplyr::filter() masks stats::filter()
x dplyr::lag() masks stats::lag()
Now What?
Congratulations! You’ve now downloaded R and started working within the R environment. Over time, you'll see how versatile and cool R is, and how it can empower you as a programmer and data analyst. You're now ready for some more advanced exercises, or to begin exploring the useful examples at R Bloggers (http://www.r-bloggers.com).
You can also join the RStudio Community at https://community.rstudio.com/ or search Google to find different flavors of the "Hello World!" exercise that other new R learners have tried. See if you can expand your code to do something more interesting, like prompt you to enter your name from the keyboard using the scan() function and have R say hello to you by name.