Intro to Coding

Part 4: Exercises

Part 1 | Part 2 | Part 3 | Part 4

Exercises

Ex: R as a Calculator

Meet Leia, a fictitious undergrad student taking Stat 20. Leia loves to drink coffee in the morning, and she brews her own coffee at home. She even has a monthly budget of $20 to cover this type of expense. As you know, we can use R to create an object or variable coffee for Leia’s budget:

coffee <- 20

Alternatively, you can also use the equals sign = as an assignment operator:

coffee = 20

Your Turn: Leia’s Expenses

Consider the bills of Leia’s fixed monthly expenses:

  • phone $80
  • transportation $20
  • groceries $600
  • rent $1800
  1. Make more assignments to create variables phone, transportation, groceries, and rent with their corresponding amounts.
TipSolution:
phone <- 80
transportation <- 20
groceries <- 600
rent <- 1800

/

  1. Now that you have all the variables, create a total object with the sum of her fixed monthly expenses.
TipSolution:
total <- phone + transportation + groceries + rent
total

/

  1. Assuming that Leia has the same expenses every month, how much would she spend during a school “semester”? (assume the semester involves five months).
TipSolution:
total * 5

/

  1. Maintaining the same assumption about the monthly expenses, how much would Leia spend during a school “year”? (assume the academic year is 10 months).
TipSolution:
total * 10

/

Ex: Taxonomy of Data and R Vectors

From the taxonomy of data, you know that we have 4 flavors of variables, and their corresponding classes in R (shown below inside parenthesis) illustrated in the following examples:

# continuous (numeric)
x1 <- c(1.2, 3.3, -0.5)

# discrete (numeric)
x2 <- c(2, 4, 6)

# ordinal (ordered factor)
x3 <- factor(c("sm", "md", "lg", "sm"), levels = c("sm", "md", "lg"))

# nominal (character or factor)
x4 <- c("strawberry", "lemon", "vanilla")
x4bis <- factor(c("strawberry", "lemon", "vanilla"))

Your Turn: Terrestrial Planets

Consider the following data set—shown in the table below—containing variables of so-called Terrestrial planets. These planets include Mercury, Venus, Earth, and Mars. They are called like this because they are “Earth-like” planets: relatively small in size and in mass, with a solid rocky surface, and metals deep in its interior.

name gravity moons
Mercury 3.7 0
Venus 8.9 0
Earth 9.8 1
Mars 3.7 2

/

  1. Consider the column name in the provided table of terrestrial planets. Use the c() function to create a character vector name containing the names of the Terrestrial planets.
TipSolution:
name = c("Mercury", "Venus", "Earth", "Mars")

/

  1. Consider the column gravity in the provided table of terrestrial planets. Use the combine function c() to make a numeric vector gravity for the Terrestrial planets.
TipSolution
gravity = c(3.7, 8.9, 9.8, 3.7)

/

  1. Consider the column moons in the provided table of terrestrial planets. Use the combine function c() to make an ordinal factor moons.
TipSolution
moons = factor(c(0, 0, 1, 2), ordered = TRUE)

/

Ex: Data Frames in R

Consider again the data set of Terrestrial planets—shown in the table below.

name gravity moons
Mercury 3.7 0
Venus 8.9 0
Earth 9.8 1
Mars 3.7 2

/

Use the vectors that you defined in the previous section in order to create a data frame planets:

TipSolution
planets = data.frame(
  "name" = name,
  "gravity" = gravity,
  "moons" = moons,
  "haswater" = haswater
)

/

Ex: Challenge

Let’s apply everything that you’ve learned so far in order to create a data frame students containing the following data, and the provided specifications listed below:

name height year resident
Leia 160 sophomore TRUE
Luke 170 freshman FALSE
Han 182 senior TRUE
Lando 178 junior FALSE

/

  • name: nominal variable (character)
  • height continuous variable (numeric)
  • year: ordinal variable (ordered factor)
  • resident: nominal variable (logical)
TipSolution
students = data.frame(
  "name" = c("Leia", "Luke", "Han", "Lando"),
  "height" = c(160, 170, 182, 178),
  "year" = factor(x = c("sophomore", "freshman", "senior", "junior"),
                  levels = c("freshman", "sophomore", "junior", "senior")),
  "resident" = c(TRUE, FALSE, TRUE, FALSE)
)

Want more practice? Studying for a quiz?

Try the “extras” for this week - on the homepage you’ll see a link to “Coding Basics” with more simple coding problems. Or click here to go there directly.

Summary

That was a lot! But we promise that this lesson will pay dividends for the rest of the semester. Coding is like the foundation of data science: your house is only as good as the foundation you build it on. Now we can focus on more fun things, as we use R to analyze data, ask questions, make plots, and generally empower our curiosity.

More good things about R (optional read):

R is one of the most powerful languages for doing statistics and data science. One of the reasons for its power and popularity is that it is both free and open-source – anyone can go see the internal gears of how it works, and anyone can propose changes to it. This turns languages like R into something that resembles Wikipedia: a collaborative effort that is constantly evolving. Extensions to the R language have been authored by professional programmers1, people working in industry and government2, professors3, and students like you4.

You’ll be writing and running code through an app called RStudio. Beyond writing R code, RStudio allows you to manage your files and author polished documents that weave together code and text. RStudio can be run through a browser and we have set up an account for you that you can access by sending a browser tab to https://stat20.datahub.berkeley.edu/ or clicking the link in the upper right corner of the course website.

References and further reading

A playful sketch of first impressions with R with dark clouds and scary R and second impression of sunny skies and happy R.
Figure 1: The arc of learning R5.

Footnotes

  1. The googlesheets4 package, which reads spreadsheet data into R was authored by Jenny Bryan, a developer at Posit: :https://googlesheets4.tidyverse.org/.↩︎

  2. The statistics office of the province of British Columbia maintains a public R package with all of their data: https://bcgov.github.io/bcdata/↩︎

  3. Dr. Christopher Paciorek in the Department of Statistics at UC Berkeley maintains a package to fit a very broad class of statistical models called Bayesian Models: https://r-nimble.org/.↩︎

  4. Simon Couch wrote the stacks package for model ensembling while an undergraduate https://stacks.tidymodels.org/index.html.↩︎

  5. R monster artwork by @allison_horst.↩︎