- Basic plotting in R
RStudio accounts are created for classroom teaching and learning ONLY. Research on this server is not allowed due to license restrictions. Login using your normal Calvin credentials. RStudio offers professional training courses designed to get you and your company up and running quickly creating analytical apps that leverage R. When you are ready to deepen your expertise, RStudio can help you and your team with three training options. Citations are then used in the article body with standard R Markdown notation, for example: @xie2015 (which references an id provided in the bibliography). Note that multiple ids (separated by semicolons) can be provided.
Getting Started in R and RStudio
R is a high-level object-oriented programming language, which is a free version of the programming language S (see a history of R). By object-oriented, we mean that everything in R is treated as an 'object'. A data frame is a specific type of object in R; so is a numeric value, or a character value, or a matrix.
We will be using RStudio, which is an integrated development environment (IDE) for R. RStudio is more user-friendly than using R directly since it keeps track of your R script file, console, plots, and history, all in one place. RStudio uses what it calls 'Projects' to organize your workflow. Each project file (.RProj) is a self-contained unit that contains R code, R objects, data files, etc. for a given project. You may want to create a separate project for each analysis in this course.
- Find Online Tutors in Subjects related to R. Get 1-to-1 learning help through online lessons. If you are looking to learn a subject similar to R, tap into the nation’s largest community of private tutors. Wyzant helps more students find face to face lessons, in more places than anyone else.
- RStudio Server Pro Take control of your R and Python code An integrated development environment for R and Python, with a console, syntax-highlighting editor that supports direct code execution, and tools for plotting, history, debugging and workspace management.
Recently, RStudio created an online workspace called RStudio Cloud. If you prefer not to download RStudio to your computer, or if you'd like to access your work from other computers, you may choose to use RStudio Cloud rather than RStudio on your computer. After you create an account and log in to RStudio Cloud, you can 'New Project' to start working in RStudio online. You will need to upload any data sets or code to the cloud using the 'Upload' button in the 'Files' pane (bottom right).
How to Learn R
There are many free resources online including:
- Coursera Free R classes: R Programming by Johns Hopkins
- Data Carpentry and Software Carpentry lessons
- R-bloggers: is a central hub of content collected from bloggers who write about R
How to Start RStudio
Once R and RStudio are installed on your computer, it opens as any other application. In Windows, go to the start menu, then find RStudio. On a Mac, open the Applications folder and click on the RStudio icon. It is also useful to create a desktop shortcut to the program.
The R Console
When you open RStudio, you will see the 'Console' window and >, R's command prompt. This indicates R is ready to evaluate a command. For example,
The command sample(1:6,1) tells R to take a sample of size 1 from the numbers 1 through 6. R responds with  5. The  says how many calculations R has done (you can ignore it). Then it gives another >, showing that it's ready for another command.
R also has a continuation prompt, +, which occurs if your command did not properly end.
R will not return to the command prompt > until you finish the command that started the continuation prompt or you hit Esc.
R has many built-in functions. When we use an R function, the syntax is as follows:
function.name( arg.name=value, .. )
For example, the 'rep' function creates a vector of repeated values:
The function has two arguments named 'x' and 'times'. We want to repeat the value 3 ten times. If we keep the arguments in the same order, we do not need to type their names:
But if we don't use the argument names, order matters:
The '#' sign is the comment character. Everything after a # is ignored by R:
Make ample use of the '#' sign to put comments in your R script files. This will help you remember what you were doing when you go back to look at your code at a later date, as well as help others understand your code.
Any objects we export from R will be saved in its working directory. We can use the commands setwd() or getwd() to set the working directory or to ask R what working directory it is using. Alternatively, we can click on the 'Files' tab to view or change the Working Directory.
Organizing R Code
You should get in the habit of writing your R commands in a R Script file before evaluating the commands in the R console. This will become apparent as you start using for loops and writing functions. From within RStudio we can open a new 'R Script' file by going to File -> New File -> R Script. When you save a script file, you should use the extension .R. Later, if you would like to run the code, you can highlight the code in the script file and click 'Run', or involving even less work, you can source the file into R without opening it. For example, if your code is saved as mycode.R, then in the R console, you can type
R Studio Online Version
if the file is in your working directory. If the file is located elsewhere on the computer, you can enter the entire file extension. We can even source in code off the web!
How to Save and Quit R
There are four types of files you might want to save from your RStudio session:
Rstudio Online Windows 10
- R script file (name.R) - your R code
- R workspace file (name.RData) - an R session containing all of the created objects in the 'Environment' pane (top right).
- R history file (name.Rhistory) - a history of the commands that were entered into the console
- R project file (name.Rproj) - your RStudio session: script files that are open, R objects and data sets, etc.
Your R script file is the R code; the workspace saves an R session with all of the created objects in the workspace; your R history file is a history of the commands that were entered into the console. When you re-open a workspace or project, you will need to re-load any necessary libraries again (using the 'library' command); thus, it is a good habit to include the code for any required libraries at the top of your script file. Note: R does not save what prints in the R console!
Basic R Commands
Here are some examples of basic R commands that you will find useful. Try typing them into the R console (each command followed by RETURN). If you get an error message of the form 'Error: Object not found', it may be because you skipped an earlier example which created the object, or because you mis-spelled the name of the object. As you work through the code and familiarize yourself with the syntax, try to understand exactly what each line of code is telling R to do. Remember that R is case-sensitive!
Creating Data Sets
Built-in Data Sets
Selecting subsets of data sets and logical operators
Operations on data sets
Probability Distributions in R
More Useful R functions
Data Input: Birth Weights
Taken from Stat Labs by Nolan and Speed, originally from the Child Health and Development Studies conducted at the Oakland, CA, Kaiser Foundation Hospital. The variables are
- bwt: baby's weight in ounces at birth
- gestation: duration of pregnancy in days
- parity: parity indicator (first born = 1, later birth = 0)
- age: mother's age in years
- height: mother's height in inches
- weight: mother's weight in pounds (during pregnancy)
- smoke: indicator for whether mother smokes (1=yes, 0=no)
The data will be read into R in 'data frame' format, which are arrays of data in which each case (here an individual) corresponds to a row, and each variable corresponds to a column. The row labels for these data frames are just row numbers, the column labels are the names of the variables. Only complete cases are included here.
Use the following command to load the data into your R session:
Check that the data were read in correctly:
We will take bwt to be the response variable. For now, consider gestation as the only predictor. (We will explore this data set in more detail, using more predictor variables, in the future.) The first step to any data analysis should be to explore the data - plots and summary statistics.
Basic Plotting in R
Let's take a look at the distribution of gestation periods using a histogram:
A histogram places each observation into pre-determined 'bins' where the height of the bin is the number of observations in that bin. Our histogram doesn't look too good - let's try a different bin size:
The option breaks=40 tells R to break up the x-axis into 40 bins. Notice that the labels on the vertical axis are counts (frequencies). We could also look at the 'density' histogram, use
When you use the freq=F argument in hist(), you are asking for the density histogram, which has total area 1. Area is proportional to relative frequency (the count divided by the total number of observations). For example, in the interval from 280 to 300, the frequency histogram shows a count of 61. The height of that interval in the density histogram is about .00247, and the width is 20. Thus the area for that interval is about .091*5 = 0.049 (4.9% of the sample), and 0.049*1236 is about 61.
We can also add a smoothed density line to a histogram:
Note that the histogram must be on the density scale in order to add a smoothed density line.
In every plot function, there are various arguments that add to the figure, such as adding titles, axes labels, or color:
For a list of all the colors in R, type:
A boxplot is really not much more than a graphical display of a 5-number summary (min, 1st quartile, median, 3rd quartile, max). The body of the box represents the location of the quartiles, with a line added at the median. The 'whiskers', or lines extending out from the box, display the distance to the furthest observations which are no more than 1.5 times the inner-quartile range (Q3-Q1) from the quartiles. Outliers are displayed as points or lines beyond the whiskers.
Note that the above plots are missing axis labels. How would you add them?
R will also do side-by-side boxplots which we can use to compare distributions of quantitative variables across categories:
Comparing Two Variables
For the most part, we will be interested not in just one variable, but the relationship between two or more variables. Depending on if the variables are quantitative or categorical, this can be done in a variety of ways.
In order to refer to variables directly by name (rather than preceding the variable name with babies$), let's attach the data set:
(Note: Many R coders do not recommend the use of the attach function since it can clutter your R workspace. Make sure you detach the data set after you are finished!)
The 'plot' function is a generic plotting function. We can feed it one variable:
or two variables (scatterplot):
or side-by-side boxplots:
or an entire data set:
What if we want to compare more than two variables? If they are all quantitative, we would need a 3-D scatterplot. However, if there are two quantitative variables and one categorical variable, we can use a scatterplot of the two quantitative variables with plot symbols denoting the levels of the categorical variable. Let's try this with gestation, bwt, and smoke.
Now that we are finished referring to the variables by name (without the babies$ prefix), let's detach the data set:
R has functions built in for most of the standard quantitative measures that we are likely to use. Those that aren't built in are easy to add.
Basic numerical measures for a data set X1, X2, X3,.., Xn, stored in an R variable named 'x'
|median (middle value)||50th percentile, i.e., a value M such that 50% of the data are less than M and 50% are greater than M.||median(x)|
|minimum||value of the smallest data point||min(x)|
|maximum||value of the largest data point||max(x)|
|p-th quantile||A value Q such that p*100% of the data are less than Q and (1-p)100% are greater than Q. Special cases:||quantile(x,p)|
|5 number summary||min, Q1, median, Q2, max||quantile(x)|
|variance||mean squared deviation from the mean||var(x)|
|standard deviation||square root of the variance; a 'typical' deviation from the mean||sd(x)|
|order statistics||data in ascending order||sort(x)|
We can easily add functions, for example to compute the inter-quartile range (IQR) = Q3-Q1:
In the iqr function defined above, the variable r will be a dataset with 2 elements, the first and third quartiles. The final expression of the function is the value returned, in this case the difference between the two quartiles.
There are also functions that are meant for two or more variables, such as correlation:
Additional Practice with Data in R
Work through the OpenIntro Introduction to Data lab to better familiarize yourself with how to work with data in base R.
- Connect to Spark from R. The sparklyr package provides a complete dplyr backend.
- Filter and aggregate Spark datasets then bring them into R for analysis and visualization.
- Use Spark’s distributed machine learning library from R.
- Create extensions that call the full Spark API and provide interfaces to Spark packages.
You can install the sparklyr package from CRAN as follows:
You should also install a local version of Spark for development purposes:
To upgrade to the latest version of sparklyr, run the following command and restart your r session:
If you use the RStudio IDE, you should also download the latest preview release of the IDE which includes several enhancements for interacting with Spark (see the RStudio IDE section below for more details).
Connecting to Spark
You can connect to both local instances of Spark as well as remote Spark clusters. Here we’ll connect to a local instance of Spark via the spark_connect function:
The returned Spark connection (
sc) provides a remote dplyr data source to the Spark cluster.
For more information on connecting to remote Spark clusters see the Deployment section of the sparklyr website.
We can now use all of the available dplyr verbs against the tables within the cluster.
We’ll start by copying some datasets from R into the Spark cluster (note that you may need to install the nycflights13 and Lahman packages in order to execute this code):
To start with here’s a simple filtering example:
Introduction to dplyr provides additional dplyr examples you can try. For example, consider the last example from the tutorial which plots data on flight delays:
dplyr window functions are also supported, for example:
For additional documentation on using dplyr with Spark see the dplyr section of the sparklyr website.
It’s also possible to execute SQL queries directly against tables within a Spark cluster. The
spark_connection object implements a DBI interface for Spark, so you can use
dbGetQuery to execute SQL and return the result as an R data frame:
You can orchestrate machine learning algorithms in a Spark cluster via the machine learning functions within sparklyr. These functions connect to a set of high-level APIs built on top of DataFrames that help you create and tune machine learning workflows.
Here’s an example where we use ml_linear_regression to fit a linear regression model. We’ll use the built-in
mtcars dataset, and see if we can predict a car’s fuel consumption (
mpg) based on its weight (
wt), and the number of cylinders the engine contains (
cyl). We’ll assume in each case that the relationship between
mpg and each of our features is linear.
For linear regression models produced by Spark, we can use
summary() to learn a bit more about the quality of our fit, and the statistical significance of each of our predictors.
Spark machine learning supports a wide array of algorithms and feature transformations and as illustrated above it’s easy to chain these functions together with dplyr pipelines. To learn more see the machine learning section.
Reading and Writing Data
You can read and write data in CSV, JSON, and Parquet formats. Data can be stored in HDFS, S3, or on the local filesystem of cluster nodes.
You can execute arbitrary r code across your cluster using
spark_apply. For example, we can apply
iris as follows:
You can also group by columns to perform an operation over each group of rows and make use of any package within the closure:
The facilities used internally by sparklyr for its dplyr and machine learning interfaces are available to extension packages. Since Spark is a general purpose cluster computing system there are many potential applications for extensions (e.g. interfaces to custom machine learning pipelines, interfaces to 3rd party Spark packages, etc.).
Here’s a simple example that wraps a Spark text file line counting function with an R function:
To learn more about creating extensions see the Extensions section of the sparklyr website.
You can cache a table into memory with:
and unload from memory using:
You can view the Spark web console using the
You can show the log using the
Finally, we disconnect from Spark:
The latest RStudio Preview Release of the RStudio IDE includes integrated support for Spark and the sparklyr package, including tools for:
- Creating and managing Spark connections
- Browsing the tables and columns of Spark DataFrames
- Previewing the first 1,000 rows of Spark DataFrames
Once you’ve installed the sparklyr package, you should find a new Spark pane within the IDE. This pane includes a New Connection dialog which can be used to make connections to local or remote Spark instances:
Once you’ve connected to Spark you’ll be able to browse the tables contained within the Spark cluster and preview Spark DataFrames using the standard RStudio data viewer:
You can also connect to Spark through Livy through a new connection dialog:
The RStudio IDE features for sparklyr are available now as part of the RStudio Preview Release.
rsparkling is a CRAN package from H2O that extends sparklyr to provide an interface into Sparkling Water. For instance, the following example installs, configures and runs h2o.glm:
Connecting through Livy
Livy enables remote connections to Apache Spark clusters. Before connecting to Livy, you will need the connection information to an existing service running Livy. Otherwise, to test
livy in your local environment, you can install it and run it locally as follows:
To connect, use the Livy service address as
method = 'livy' in
spark_connect. Once connection completes, use
sparklyr as usual, for instance:
Once you are done using
livy locally, you should stop this service with:
To connect to remote
livy clusters that support basic authentication connect as: