Example 01: Up and Running with R

We will be working with the most recent stable versions of R and RStudio, as well as with a number of additional packages. You will need to install R, RStudio, and the necessary packages on your own computer.

1. Install R on your computer

Begin by installing R (http://cloud.r-project.org). Choose the version appropriate for your computing platform:

2. Install RStudio on your computer

3. Installing some additional packages

  • Once R and RStudio are installed, launch RStudio. Either carefully type in or copy-and-paste the following lines of code at R’s command prompt, located in the RStudio window named “Console”, and then hit return. To copy this chunk of code, mouse over the code click the clipboard icon, , that appears in the top right corner of the chunk.
course_packages <- c("tidyverse", "babynames", "broom",
    "gapminder", "here", "janitor", "naniar", 
    "palmerpenguins", "skimr", "slider", "socviz",
    "usethis", "visdat","reprex", "remotes")

install.packages(course_packages, repos = "http://cran.rstudio.com")

data_packages <- c("kjhealy/covdata", "kjhealy/congress", "kjhealy/nycdogs", 
                   "kjhealy/ukelection2019", "kjhealy/uscenpops")


remotes::install_github(data_packages)

Installing these packages may take a little time. Once you have completed this step, you’ll be ready to begin.

4. Examples from the slides

Arithmetic:

Logic:

Take care:

But now try 3 < 5 & 1, where your intention is “Three is less than five and also less than one [True or False?]”

Instead:

You have to make your comparisons explicit.

Objects:

Functions are objects too.

Assignment:

Assignment with equals:

On the other hand, = has a different meaning when used in functions.

I’m going to use <- for assignment throughout.

Just be consistent either way.

Special operators

For example, matrix multiplication is %*%

Why %*%? In R the notation %<SOMETHING>% is used for some operators, including custom operators.

But the thing in between the % % can be lots of things. E.g.,

And we can define our own, too

Vector arithmetic

Packages

Packages are loaded into your working environment using the library() function:

You need only install a package once (and occasionally update it):

## Do at least once for each package. Once done, not needed each time.
install.packages("palmerpenguins", repos = "http://cran.rstudio.com")

## Needed sometimes, especially after an R major version upgrade.
update.packages(repos = "http://cran.rstudio.com")

But you must load the package in each R session before you can access its contents: