1 of 34

Intro to R and RStudio

Sarah Ryley

Boston Globe

sarah.ryley@globe.com

2 of 34

Download R and R Studio: https://posit.co/download/rstudio-desktop/

​

R is an open-source programming language specifically designed for statistical computing and graphics.

​

R Studio is an open-source application with dashboards and tools that make using R easier and more intuitive.

3 of 34

Tips for learning R:

  • R is a language. You learn it by using it. Don’t expect to remember everything from this class. Focus on getting comfortable with the syntax, terminology, and concepts so you’re better equipped to learn on your own.
  • Try to figure things out on your own before asking for help.
  • Google is your best tool. The web has endless free resources on R, such as documentation, cheatsheets, tutorials (written, interactive, video), and “help” forums like Stack Overflow. Google: “How to join tables in R”
  • Error messages are also learning opportunities. Google the error message or what you’re experiencing. It may be frustrating, but by figuring out what went wrong, you’ll learn more about how R and data work.

4 of 34

5 of 34

“Packages”

​

Packages are sets of code (and sometimes data) in the R programming language that together make it easier to do specific tasks, like cleaning data, making graphics, statistical modeling, and mapping. Some packages are designed for all types of users, while others are designed for needs in specific fields, like soil sampling, clinical trials, and social network analysis.

​

The CRAN repository (Comprehensive R Archive Network) repository has nearly 20,000 packages, and thousands more are published elsewhere.

​

You install packages using a command in R Studio; not by downloading them from your web browser.

​

6 of 34

Tidyverse is a set of core packages.

​

Installing tidyverse installs all 7 of these packages. Read through the tip sheets for each package to familiarize yourself with what they do.

  • ggplot2 - makes graphics
  • dplyr - manipulates and analyzes data
  • tidyr - restructures data
  • readr - reads and writes data
  • purrr - work with functions and vectors
  • tibble - creates data frames
  • stringr - cleans and investigates data
  • forcats - works with factors

​

7 of 34

Other packages

​

lubridate

​

​

8 of 34

9 of 34

Create a new R project in RStudio

  • Open RStudio
  • File -> New Project -> New Directory -> New Project
  • Directory Name: R_Intro
  • Create project as a subdirectory of: Desktop (This is just so it’s easy for us to find)
  • Click “Create Project”
  • The folder will appear on the desktop (or wherever you created the directory). This is your project folder. You can create new folders, drag and drop files into the folder, and change file names outside of R just as you would any other folder. Changes made from the desktop will be immediately reflected in your R project folder.
  • Tip: Avoid spaces in folder or file names, it makes writing script more tedious. Keep your project folder clean! I like to keep folders called: “Original_Data” with untouched raw data; “Documentation” with documentation such as the record layout, code definitions, and correspondences from records officers that explain things; and “Output” for any type of output files.

10 of 34

R Studio work environment:

You can type commands directly into the console and see the output.

Environment shows active objects, such as datasets and functions. History shows the commands you’ve used so far, even the ones you’ve deleted. Connections connects to and explores existing data sources

Files shows the files and folders in your R Project folder. Plots shows graphics. Packages lists packages and add-ons. Help gives links to help references.

R Scripts and data view: This panel is where you open and create script files, and view your data.

11 of 34

Create a new R Markdown file:

​

  • File -> New File -> R Markdown
  • Call it 01_Intro. When you’re creating a data project, it’s a good idea to name your files in the order of the steps taken. You’ll notice this appears at the top of the file, along with your name and data. You can edit this if you want.
  • Save the file: File -> Save As -> 01_Intro (I always save right away so I can save with Command-S as I’m working)
  • Note: R Markdown is a personal preference, because I like the interface for writing notes and breaking up code into related functions. You can also convert your R Markdown file into beautiful presentations. Here’s a gallery with some examples.

​

​

Add your data to the project folder:

​

  • From the desktop, create a folder in your R project folder called “Original_Data” and drag the data into the folder.

​

12 of 34

Create a new “code chunk”

A “chunk” in R Markdown is a way to break up and organize groups of commands. You can either run one command by hitting command-return somewhere within that command, or you can run the entire chunk by clicking the green arrow on the top-right of the chunk. You can run the entire file by clicking the “Run” button at the top of the file. You can (and should!) write notes between the chunks — for future reference and to make it easier for others to understand your work. (See R Markdown tutorials for how the white space translates in a presentation.) When you write a command that produces a table or graphic, it will appear in the white space beneath the chunk.

​

```{r} Starts a new chunk. Those characters are called “graves”. They are used a lot in R and can be found on the same key as the ~ character. Give your chunk a name. I name the first one “setup” because it sets up my project.

​

``` Ends the chunk

​

R won’t run the code inside the chunk unless you have both the beginning and end!

13 of 34

Install tidyverse and load the tidyverse library

install.packages A command to install an R package. You only need to install a package once, although you may need to reinstall the package if there have been any updates. The name of the package goes in quotes.

​

tidyverse Tidyverse is actually a collection of some of the most used R packages, that do things like loading, cleaning and plotting data.

​

library A command to load a package’s library. You need to do this every time you open the file. Quotes are not used for the name of the package.

​

Everything is case-sensitive! R would have no idea what you’re talking about if you typed “library(TIDYVERSE)”.

14 of 34

Load data

<- Puts something new into your Environment panel that you can work with, in this case a dataset that we’re calling “population.” The name goes to the left of the arrow. Try to make your names something short but meaningful so your code is easier to follow.

​

read_csv Is a function that does what the name implies. (There are packages specifically for reading other file types, such as Excel, SQL, SPSS and flat txt files.)

​

Put the name of the file, including the path, in quotes.

​

/ is a path indicator. In this case, it’s saying, go into the “Original_Data” folder and grab the csv “nyc_pop_community_districts.csv”.

​

​

15 of 34

Once you load the data, you’ll get a bunch of useful information in the “Environment” pane. This dataset has 59 observations (rows) and 8 variables (columns). By clicking the down arrow, you’ll see the name of each column, and the type of data in that column: character, factor, integer, numeric, logical, date, etc. Certain functions can only run on certain data types. Here’s a great guide on this. If you double-click the table name, it will appear in the top left panel.

16 of 34

You can also print the column names in your script and console panels:

colnames is the function that says “print the column names”

population inside the parenthesis, write what we’re performing the function on — the “population” dataset. (You can only perform function on things in your Environment pane.)

​

Tip: The columns are numbered because, for many functions, you can call columns by either their name or their number (position). Using the numbers are especially helpful if you’re performing a function on a range of columns — for example, if you want to add columns 4-8, you could just write: sum(4:8). Generally, I use the name so I don’t have to go back through the entire script if I make an edit that changes the position of the columns.

17 of 34

Let’s write some notes on this project and the source data as a gift to our future selves! Here are a few things that I typically include:

18 of 34

Create a basic chart:

​

hist the histogram command

​

$ Signifies a column within a table. The table name comes first, then the column name.

​

` The grave key is used around column names when there are spaces or numbers in the column. You’ll notice if you remove the grave ket that “2010” turns blue, because R is reading it as a number.

​

Now we’re going to add a few more arguments to the histogram command, within the parenthesis and separated by commas. “main” indicates the chart title and “xlab” indicates the title of the x axis.

​

​

19 of 34

You can make way cooler charts than this...

Here’s a good set of examples that are easy to follow using plotly:

https://plot.ly/r/

20 of 34

A command using “pipes”:

​

population %>% group_by(Borough) %>% tally(`2010_Population`)

%>% is a “pipe”. You can think of it as saying, “and then do this”. The table name always comes first, In this case “population”. When you use pipes, you only need to write the table name once.

group_by is a function that groups a variable, in this case by borough, because the data has multiple records for each borough, one per community district.

tally is a function that means “add”

`2010_Population` The ` symbol is called a “grave accent”. It signifies that this is a column name. If you remove the `` you’ll notice “2010” turns blue. R is confused and reads this as a number that we’re going to run a calculation on. So the `` tells R that, no, this is a column name. You would also do this if there are spaces in the column names.

We’re saying: “Take the table called “population”, THEN group the data so there is one row per borough, THEN add the 2010 population.

​

21 of 34

Notice that I left notes for myself and others: I wrote what I’m calculating above the chunk, and beneath the function, a note on the results. This is helpful for a number of reasons:

  • You’ll understand what’s happening with your script when you come back to it later. This is especially helpful when you need to fix something.
  • Noting the results is helpful as a check to yourself. If you go back and make changes, you want to make sure you keep getting the same number of records, for example.
  • It makes it easier for other people to understand your script if you’re sharing or publishing your work.

22 of 34

How do I know FOR SURE that there’s one row per community district? With “n_distinct”.

population %>%

group_by(Borough) %>%

count(n_distinct(CD_Name))

​

count is the primary function for this line of code. We’re counting the number of records per Borough.

​

n_distinct means “count the number of distinct” CD_Names per borough.

​

n is shorthand in R for “number”.

​

The resulting table has a column for both the number of distinct CD_Names per borough, and the number of records (“n”) per borough. They match, which means that each borough-CD name combination only appears once in this dataset.

​

23 of 34

24 of 34

$ Signifies a column within a table. The table name comes first, then the column name.

​

<- What we want to create is on the left side of the arrow; what we are doing to create that thing is on the right side of the arrow.

​

This math is pretty simple, we’re subtracting one column from another.

Creating a new column and basic calculations:

25 of 34

You can see the column has been successfully created by checking the global environment:

Our new column automatically appears.

26 of 34

The new column also automatically appears in the table view. You can click the arrow button next to the column name to sort, showing the community district with the largest population growth or decline.

27 of 34

You can also filter your data in the table view:

28 of 34

Quiz:

​

Create a new column called “population$percent_pop_change_1970_2010” that calculates the percent change in population from 1970 to 2010 by dividing the column “1970_Population” into the column that we just created, “population$pop_change_1970_2010”.

29 of 34

Answer:

30 of 34

Formatting numbers:

​

population$`%_change_format` <- I’m creating a new column with the formatted number.

Format The format command.

​

digits: How many significant digits of numeric values to show.

​

nsmall: The minimum number of digits after the decimal point.

​

More ways to format numbers: (Link)

​

31 of 34

The reformatted number is now a character, which means we can do math on it, or even sort it…

​

We need to add the “as.numeric” command, nesting the other command in parenthesis.

​

​

Tip: If a command isn’t working, make sure you are using the proper data format. Some commands only work on certain formats, and if you’re joining or binding tables, the corresponding columns have to be in the same format.

32 of 34

Adding and dropping columns

We’re creating a new table called “pop_drop”.

subset is the function to add and drop columns. It’s a “subset” of the other dataset.

Inside the parenthesis, the name of the dataset we’re using goes first, then a comma, then the select command.

c indicates “columns”, the - symbol indicates we’re removing them. If we wanted to list the columns we’re keeping, we would not use the - symbol.

Notice each column is separated by a comma, and that there are as many closing parenthesis as opening parenthesis.

33 of 34

Writing a csv:

We’re using the pipe function to tell R to write a csv using the table called “population.”

The name we’re giving the csv is in parentheses and quotes.

Similar to “read_csv”, if we wanted to put the new csv in a folder, we would use the / symbol to create a path.

Now you’ll see the csv appear in the folder.

​

34 of 34

Download R2: Analysis and Plotting in R

​

https://bit.ly/2XIf0Wt

​