3 R basics
R is a programming language, one specifically geared toward statistical analysis. Like all programming languages, it has certain built-in functions and you can interact with it in multiple ways. The first, and most basic, is the console.
Think of the console like talking directly to R. It’s direct, but it has some drawbacks and some quirks we’ll get into later. For now, try typing this into the console and hit enter:
2+2
[1] 4
Congrats, you’ve run some code. It’s not very complex, and you knew the answer before hand, but you get the idea. We can compute things. We can also store things. In programming languages, these are called variables. We can assign things to variables using <-
. And then we can do things with them. The <-
is a called an assignment operator.
Try this in your console.
<- 2
number
* number number
[1] 4
Now assign a different number to the variable number. Try run number * number
again. Get what you expected?
We can have as many variables as we can name. We can even reuse them (but be careful you know you’re doing that or you’ll introduce errors). Try this in your console.
<- 1
firstnumber <- 2
secondnumber
+ secondnumber) * secondnumber (firstnumber
[1] 6
We can store anything in a variable. A whole table. An array of numbers. A single word. A whole book. All the books of the 18th century. They’re really powerful. We’ll explore them at length.
3.1 Adding libraries, part 1
The real strength of any given programming language is the external libraries that power it. The base language can do a lot, but it’s the external libraries that solve many specific problems – even making the base language easier to use.
For this class, we’re going to need several external libraries.
The first library we’re going to use is called Swirl. So in the console, type install.packages('swirl')
and hit enter. That installs swirl.
Now, to use the library, type library(swirl)
and hit enter. That loads swirl. Then type swirl()
and hit enter. Now you’re running swirl. Follow the directions on the screen. When you are asked, you want to install course 1 R Programming: The basics of programming in R. Then, when asked, you want to do option 1, R Programming, in that course.
When you are finished with the course – it will take just a few minutes – type 0 to exit (it will not be clear that’s what you do when you are done).
3.2 Adding libraries, part 2
We’ll mostly use two libraries for analysis – dplyr
and ggplot2
. To get them, and several other useful libraries, we can install a single collection of libraries called the tidyverse. Type this into your console: install.packages('tidyverse')
NOTE: This is a pattern. You should always install libraries in the console.
Then, to help us with learning and replication, we’re going to use R Notebooks. So we need to install that library. Type this into your console: install.packages('rmarkdown')