Skip to main content

R Basics Review

A reference for working in R and RStudio

About this guide

This page is an optional review of the basic R skills used throughout the course.

It introduces no new statistical material and there is nothing to submit. Use it while following the R Basics recording, print it if that is helpful, or return to individual sections when you need a reminder.

The examples begin with a tiny survey so the R commands are easy to see. At the end, we apply the same workflow to the October Univision/YouGov Texas Poll.

Note

Video recordings: Part 1 · Part 2 — coming soon

The basic workflow

Most of the R work in this course follows the same general sequence:

Load → inspect → filter → summarize → compare

You do not need to memorize every command. You should learn to recognize the workflow and know how to inspect your data when you are unsure what to do next.

1. RStudio: Source and Console

The two most important RStudio panes for this course are:

  • Source: where you write and save code.
  • Console: where R executes code.

Write your code in the Source pane whenever possible.

To run a line from the Source pane:

  • Windows: Ctrl + Enter
  • Mac: Command + Enter

R can perform basic calculations:

2 + 2
10 / 2
5 * 6

2. Objects

Objects let R remember values.

x <- 10

Display the object:

x

Create another object:

y <- 5

Use both objects:

x + y

The basic structure is:

object_name <- value

<- means assign this value to this object.

3. Vectors and Functions

A vector stores several values together.

ages <- c(18, 19, 20, 21, 22)

Display it:

ages

Common functions include:

mean(ages)
min(ages)
max(ages)
length(ages)

The basic idea is:

function(object)

A function does something to an object.

4. A Tiny Survey

Create a small survey dataset:

survey <- data.frame(
  id = 1:10,
  gender = c(
    "Woman", "Man", "Woman", "Man", "Woman",
    "Man", "Woman", "Man", "Woman", "Man"
  ),
  approve = c(
    1, 0, 1, 1, 1,
    0, 0, 1, 1, 0
  ),
  age = c(
    22, 31, 27, 45, 38,
    51, 29, 34, 42, 25
  )
)

Look at it:

survey

A data frame is similar to a spreadsheet:

  • each row is usually a respondent or observation;
  • each column is a variable.

5. Inspect Before You Analyze

Three useful commands:

head(survey)
names(survey)
str(survey)

They answer different questions:

Command Question
head() What do the first few rows look like?
names() What variables are available?
str() How is each variable stored?

A useful rule:

Before analyzing a dataset, look at it.

6. Accessing One Variable

Use $ to select a variable inside a data frame:

survey$age

Calculate the mean:

mean(survey$age)

Now look at approval:

survey$approve

Because this variable uses:

  • 1 = approve
  • 0 = do not approve

its mean is also the proportion approving:

mean(survey$approve)

7. Packages

Many commands used in this course come from the tidyverse.

Load it with:

library(tidyverse)

If R says the package is not installed, install it once:

install.packages("tidyverse")

Then load it:

library(tidyverse)

Install a package once on a computer.
Load it at the beginning of a new R session.

8. The Pipe

The pipe is:

|>

Read it as then.

For example:

survey |>
  filter(gender == "Woman")

Read this as:

Start with survey, then keep respondents whose gender is Woman.

9. Filtering Rows

Keep only women:

survey |>
  filter(gender == "Woman")

Keep only men:

survey |>
  filter(gender == "Man")

Keep respondents older than 30:

survey |>
  filter(age > 30)

Keep only respondents who approve:

survey |>
  filter(approve == 1)

Two symbols that look similar have different meanings:

<-

means assign.

==

means is equal to.

10. Saving a New Dataset

You can save the result of a filter as a new object:

women <- survey |>
  filter(gender == "Woman")

Display it:

women

The original dataset still exists:

survey

A common pattern is:

new_object <- old_object |>
  some_function()

11. Summarizing

Calculate overall approval:

survey |>
  summarize(
    approval = mean(approve)
  )

Approval among women:

survey |>
  filter(gender == "Woman") |>
  summarize(
    approval = mean(approve)
  )

Approval among men:

survey |>
  filter(gender == "Man") |>
  summarize(
    approval = mean(approve)
  )

12. Comparing Groups

Instead of filtering each group separately, use group_by():

survey |>
  group_by(gender) |>
  summarize(
    approval = mean(approve)
  )

Read this from top to bottom:

  1. Start with survey.
  2. Divide respondents into gender groups.
  3. Calculate approval separately within each group.

13. Counting Categories

Use count() to see how many observations fall into each category.

survey |>
  count(gender)
survey |>
  count(approve)

Count combinations:

survey |>
  count(gender, approve)

14. Missing Values

In R, missing values are usually represented by:

NA

Create one for demonstration:

survey$age[3] <- NA

Now:

mean(survey$age)

returns NA.

Tell the function to remove missing values for the calculation:

mean(survey$age, na.rm = TRUE)

You will use:

na.rm = TRUE

frequently with survey data.

15. Basic Graphics

A simple bar chart:

ggplot(survey, aes(x = gender)) +
  geom_bar()

A histogram of age:

ggplot(survey, aes(x = age)) +
  geom_histogram()

The basic structure is:

ggplot(DATA, aes(...)) +
  GEOM

You can worry about colors, labels, and other styling after the graph works.

16. Working Directory and Files

Before reading a file, check where R is looking:

getwd()

See the files in that folder:

list.files()

If your file does not appear in list.files(), R will not find it by filename alone.

17. Reading a CSV

If texas_poll.csv is in your working directory:

texas <- read_csv("texas_poll.csv")

Immediately inspect the data:

head(texas)
names(texas)
glimpse(texas)
Tip

If you do not know a variable name, do not guess. Use names() and consult the codebook.

18. Common Errors

object not found

Usually R cannot find an object with the name you typed.

Check:

  • spelling;
  • capitalization;
  • whether the line that created the object was actually run.

could not find function

The package containing the function may not be loaded.

Try:

library(tidyverse)

File does not exist

Check:

getwd()
list.files()

Make sure the file is actually in the folder R is using.

Capitalization matters

These are three different names:

survey
Survey
SURVEY

R is case-sensitive.

Debug one step at a time

Do not try to fix ten lines at once.

Run one line. Confirm that it works. Then move to the next one.

19. Practice Without Submitting Anything

Try these using the tiny survey data:

  1. Calculate average age.
  2. Count the number of women.
  3. Calculate the overall proportion approving.
  4. Calculate approval among women.
  5. Calculate approval among men.
  6. Create a dataset containing only respondents over age 30.
  7. Create a table showing approval separately for men and women.

These are for practice only.

20. Transfer to the Texas Poll

The October Texas poll uses the same R workflow.

Download the Texas poll CSV

Open the codebook

Load the file:

texas <- read_csv("texas_poll.csv")

Inspect it:

names(texas)

Create the Latino analytic sample:

latino <- texas |>
  filter(!is.na(weight_hisp))

Check the governor vote variable:

latino |>
  count(govvote26_full)

Create a 0/1 Hinojosa indicator:

latino <- latino |>
  mutate(
    hinojosa = if_else(
      govvote26_full == 1,
      1,
      0,
      missing = NA_real_
    )
  )

Calculate unweighted support:

latino |>
  summarize(
    support = mean(
      hinojosa,
      na.rm = TRUE
    )
  )

Compare by gender:

latino |>
  group_by(gender) |>
  summarize(
    support = mean(
      hinojosa,
      na.rm = TRUE
    )
  )
Note

These are unweighted practice estimates. The weighting lab shows how to produce the survey estimates used for substantive reporting.

Quick Reference

Load a package

library(tidyverse)

Read a CSV

data <- read_csv("file.csv")

Look at variables

names(data)
glimpse(data)

Keep some rows

data |>
  filter(...)

Calculate one summary

data |>
  summarize(...)

Compare groups

data |>
  group_by(...) |>
  summarize(...)

Count categories

data |>
  count(...)

Remove missing values from a calculation

mean(variable, na.rm = TRUE)

The key workflow is:

Load → inspect → filter → summarize → compare