coffee <- 20Intro to Coding
Part 4: Exercises
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:
Alternatively, you can also use the equals sign = as an assignment operator:
coffee = 20Your Turn: Leia’s Expenses
Consider the bills of Leia’s fixed monthly expenses:
- phone $80
- transportation $20
- groceries $600
- rent $1800
- Make more assignments to create variables
phone,transportation,groceries, andrentwith their corresponding amounts.
phone <- 80
transportation <- 20
groceries <- 600
rent <- 1800/
- Now that you have all the variables, create a
totalobject with the sum of her fixed monthly expenses.
total <- phone + transportation + groceries + rent
total/
- Assuming that Leia has the same expenses every month, how much would she spend during a school “semester”? (assume the semester involves five months).
total * 5/
- Maintaining the same assumption about the monthly expenses, how much would Leia spend during a school “year”? (assume the academic year is 10 months).
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 |
/
- Consider the column name in the provided table of terrestrial planets. Use the
c()function to create a character vectornamecontaining the names of the Terrestrial planets.
name = c("Mercury", "Venus", "Earth", "Mars")/
- Consider the column gravity in the provided table of terrestrial planets. Use the combine function
c()to make a numeric vectorgravityfor the Terrestrial planets.
gravity = c(3.7, 8.9, 9.8, 3.7)/
- Consider the column moons in the provided table of terrestrial planets. Use the combine function
c()to make an ordinal factormoons.
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:
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)heightcontinuous variable (numeric)year: ordinal variable (ordered factor)resident: nominal variable (logical)
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
Hands on Programming with R by Garret Grolemund. A friendly introduction to the R language with fun examples.
The official (somewhat dense) documentation fo the R language. https://cran.r-project.org/doc/manuals/r-release/R-lang.html
R for Data Science by Hadley Wickham and Garrett Grolemund. A comprehensive but approachable guide to doing data science with R. A good reference once you’re deeper into this course..
Footnotes
The
googlesheets4package, which reads spreadsheet data into R was authored by Jenny Bryan, a developer at Posit: :https://googlesheets4.tidyverse.org/.↩︎The statistics office of the province of British Columbia maintains a public R package with all of their data: https://bcgov.github.io/bcdata/↩︎
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/.↩︎
Simon Couch wrote the
stackspackage for model ensembling while an undergraduate https://stacks.tidymodels.org/index.html.↩︎R monster artwork by @allison_horst.↩︎