Coding basics - Extra Practice
- You don’t have to do all of these. (Or any, for that matter). They are here for you to do as many as you need to get the hang of it, to practice for quizzes, etc.
- Skip around if you like.
- These questions practice the R coding basics from the Taxonomy of Data tutorial: arithmetic, assignment, object classes, functions, vectors, data frames, and knowing when R prints output.
Arithmetic
Exercise 1
What does R return?
4 + 7 * 2Show answer
R returns 18. Multiplication happens before addition: 7 * 2 is 14, then 4 + 14 is 18.
Exercise 2
What does R return?
(4 + 7) * 2Show answer
R returns 22. Parentheses happen first: 4 + 7 is 11, then 11 * 2 is 22.
Exercise 3
What does R return?
2 ^ 3 + 1Show answer
R returns 9. The ^ symbol is an exponent, so 2 to the third power. Exponents happen before addition: 2 ^ 3 is 8, then 8 + 1 is 9.
Exercise 4
Write one line of R code that computes the number of minutes in 3.5 hours.
Show answer
3.5 * 60This returns 210.
Exercise 5
Write one line of R code that computes the natural log of 100. Hint: the ln function takes the natural log (log base \(e\))
Show answer
log(100)By default, log() computes the natural logarithm.
Exercise 6
Now compute the log base 10 of 100. There are two solutions, try to guess and figure it out.
Show answer
Solution 1:
log10(100)This correctly returns 2. log10 is a native R function for taking logs of base 10.
Solution 2:
Alternatively, you can take logs of ANY base by passing (regular) log a second argument, e.g.
log(100, 10)This is saying \(log_{10}{100}\)
Another example with a different base:
log(16, 2)This computes \(log_{2}{16}\), which is 4.
Exercise 7
What does R return?
10 / 2 + 3 * 4Show answer
R returns 17. Division and multiplication happen before addition: 10 / 2 is 5, 3 * 4 is 12, and 5 + 12 is 17.
Assignment and Changing Values
Exercise 8
After running these lines, what is stored in x?
x <- 5
x + 3Show answer
This will print 8 to the screen, but x is still 5. The second line looks up what x is, adds 3 to it, and prints the result. x will not change unless you set it to something new with <-.
Exercise 9
After running these lines, what is stored in total?
coffee <- 20
snack <- 6
total <- coffee + snackShow answer
total stores 26.
Exercise 10
After running these lines, what is stored in total?
coffee <- 20
snack <- 6
total <- coffee + snack
snack <- 10Show answer
total still stores 26. Changing snack later does not automatically rerun the earlier assignment to total.
Exercise 11
After running these lines, what is stored in total?
coffee <- 20
snack <- 6
total <- coffee + snack
snack <- 10
total <- coffee + snackShow answer
total stores 30. The final line reruns the calculation using the current values of coffee and snack.
Exercise 12
Which of these are valid object names in R?
budget
budget_2026
2026_budget
my budget
coffee2Show answer
Valid names: budget, budget_2026, and coffee2.
Invalid names: 2026_budget starts with a number, and my budget uses a space, which makes R interpret it as two different things: my and budget
Exercise 13
Write code that stores the value 1800 in an object named rent, then stores five times this value semester_rent.
Show answer
rent <- 1800
semester_rent <- rent * 5After this code, semester_rent stores 9000.
Exercise 14
After running these lines, what is stored in a and b?
a <- 3
b <- a + 4
a <- 10Show answer
a stores 10 and b stores 7. The assignment to b used the old value of a, and b does not update automatically when a changes.
Object Classes and Data Types
Exercise 15
What class will R report?
class(42)Show answer
R reports "numeric".
Exercise 16
What class will R report?
class("42")Show answer
R reports "character". The quotation marks make "42" a blob of text, not a number.
Exercise 17
What happens if you run this code?
"42" + 8Show answer
R gives an error because "42" is a character string (text blob). Arithmetic works on numbers, not strings. It’s like trying to to add “apple” to the number 6. It makes no sense.
The specific error it gives is: “Error in”42” + 8 : non-numeric argument to binary operator”
The + is the “binary operator.” It does something (“operates”) on two different quantities (hence, “binary”). It’s saying that it needs both things to be numbers - not one text blob and one number.
Exercise 18
What class will R report?
class(c("Adelie", "Gentoo", "Chinstrap"))Show answer
R reports "character". Even though this is a vector containing many strings, the class function just tells you what kind of “stuff” is in the vector. It doesn’t tell you that it’s a vector.
Exercise 19
What will the resulting dataframe look like? Make a little drawing on paper, or describe it verbally before checking your answer.
df <- data.frame(name = c("Ava", "Ben"), score = c(9, 7))Show answer
| name | score |
|---|---|
| Ava | 9 |
| Ben | 7 |
Functions and Their Responses
Exercise 20
Identify the function(s), argument(s), and return value (if any).
sqrt(49)Show answer
The function is sqrt(), which is passed is one argument: 49. It will return 7.
Exercise 21
Identify the function(s), argument(s), and return value (if any).
mean(c(10, 20, 30))Show answer
The first function that you see is mean. It expects one argument: a vector of numbers.
That vector is created right on the spot, using the c function, which is given three arguments: 10, 20, and 30, and it returns a vector (container with [10, 20, 30] in it)
Finally mean can compute the average and returns 20.
Exercise 22
Identify the function(s), argument(s), and return value (if any).
length(c("red", "blue", "green", "blue"))Show answer
R returns 4, the number of elements in the vector.
There are two functions being called here:
cwhich is given four arguments, each of which is a string, and returns a vector with these strings.- This vector becomes the input for
length, which just counts and returns how many things are in the vector (4 here).
Exercise 23
Write one line of code that simultaneously calculates the square root of each of these numbers: 16, 25, and 36.
Show answer
sqrt(c(16, 25, 36))R returns c(4, 5, 6).
This one is different because of how sqrt works. If you give it just a number (e.g., sqrt(4)) it will give you one number back (2). But if you give it a vector of numbers, it will return a vector with the square roots of all the numbers.
Exercise 24
What does R return?
c(1, 2, 3) * 10Show answer
R returns c(10, 20, 30). Similar to sqrt, when multiplication * is used on a vector, R multiplies once for each value in the vector.
Exercise 25
What does R return?
c(1, 2, 3) + c(10, 20, 30)Show answer
R returns c(11, 22, 33). When things like + or * are given two vectors, it returns a vector of the result for each corresponding pair.
Exercise 26
What class will R report?
mixed <- c(1, "two", 3)
class(mixed)Show answer
R reports "character". A vector must store one basic type, so R converts the numbers to character strings.
Essentially, when you ran mixed <- c(1, "two", 3), R thought, “Well those aren’t all the same type of thing. Can I convert them all to the same type? I guess they can all be text (character strings), so lets do that.”
Run this cell to see the conversion:
Data Frames
Exercise 27
Create a data frame called pets that has information about three different pets: a 4-year-old cat named Milo, a 2-year-old dog named Luna, and a 7-year-old cat named Nori. We’ve written some of it for you, just fill in the blanks. It may help think about what the final dataframe will look like.
Show answer
pets <- data.frame(
name = c("Milo", "Luna", "Nori"),
age = c(4, 2, 7),
species = c("cat", "dog", "cat")
)You could also do it this way:
name <- c("Milo", "Luna", "Nori")
age <- c(4, 2, 7)
species <- c("cat", "dog", "cat")
pets <- data.frame(name, age, species)The resulting dataframe will look like:
| name | age | species |
|---|---|---|
| Milo | 5 | cat |
| Luna | 2 | dog |
| Nori | 7 | cat |
Exercise 28
In the pets data frame from the previous question, what is the unit of observation?
Show answer
The unit of observation is one pet. Each row stores information about one pet. This may seem stupid/trivial here, but for every dataset you’re ever given, ask yourself: what does one row represent?
Exercise 29
In this modified pets dataframe, what is a unit of observation?
| name | date | age | weight_pounds |
|---|---|---|---|
| Milo | 1 | 12 | cat |
| Milo | 2 | 13 | cat |
| Milo | 3 | 13 | cat |
| Luna | 2 | 40 | dog |
| Luna | 4 | 44 | dog |
| Luna | 5 | 45 | dog |
| Nori | 7 | 18 | cat |
Show answer
It may be that, for example, we have data on many pets through many check-ins with the veterinarian. In which case the dataset may look like:
Exercise 30
Write code to create this data frame.
| city | temperature | weather |
|---|---|---|
| Berkeley | 64 | cloudy |
| Oakland | 67 | sunny |
| Richmond | 63 | foggy |
Make city and weather character vectors and temperature numeric.
Show answer
city <- c("Berkeley", "Oakland", "Richmond")
temperature <- c(64, 67, 63)
weather <- c("cloudy", "sunny", "foggy")
weather_df <- data.frame(city, temperature, weather)Exercise 31
What happens if you try to create this data frame?
data.frame(
name = c("A", "B", "C"),
score = c(10, 12)
)Show answer
R gives an error because the columns have different lengths. There are three names, but only two scores, so R doesn’t have a full table of data. All rows have to have the same number of columns.
Exercise 32
Write code to create this data frame with an ordered factor for year.
| name | height | year |
|---|---|---|
| Leia | 160 | sophomore |
| Luke | 170 | freshman |
| Han | 182 | senior |
| Lando | 178 | junior |
Show answer
students <- data.frame(
name = c("Leia", "Luke", "Han", "Lando"),
height = c(160, 170, 182, 178),
year = factor(
c("sophomore", "freshman", "senior", "junior"),
levels = c("freshman", "sophomore", "junior", "senior"),
ordered = TRUE
)
)What Prints?
Exercise 33
Which lines print output to the console?
x <- c(5, 2)
x
c(5, 2)Show answer
The second and third lines print output. The assignment line stores a value but does not print it.
Exercise 34
Which lines print output to the console?
scores <- c(10, 20, 30)
mean(scores)
avg <- mean(scores)
avgShow answer
The second and fourth lines print output. The first and third lines are assignments, so they do not print.
Exercise 35
What appears in the console?
answer <- 2 ^ 4Show answer
Nothing prints to the console. The value 16 is stored in answer.
Exercise 36
What appears in the console?
answer <- 2 ^ 4
answerShow answer
R prints 16 on the second line because typing an object’s name asks R to display the object.
Exercise 37
Which lines print output to the console?
species <- factor(c("Adelie", "Gentoo"))
class(species)
levels(species)
penguins <- data.frame(species)Show answer
The second and third lines print output. The first and fourth lines are assignments, so they do not print.
Exercise 38
Write two lines of code that store c(3, 6, 9) in values and then print the mean to the console.
Show answer
values <- c(3, 6, 9)
mean(values)The first line stores the vector. The second line prints 6.
Exercise 39
Write two lines of code that store c(3, 6, 9) in values and store the mean in values_mean without printing the mean.
Show answer
values <- c(3, 6, 9)
values_mean <- mean(values)Both lines are assignments, so neither line prints the mean.
Exercise 40
What class will R report?
resident <- c(TRUE, FALSE, TRUE)
class(resident)Show answer
R reports "logical". TRUE and FALSE are logical values, not character strings.
Exercise 41
What class will R report?
resident <- c("TRUE", "FALSE", "TRUE")
class(resident)Show answer
R reports "character". The quotation marks make these strings, not logical values.
BONUS CHALLENGE: Write your own function
Programmers constantly write their own functions to perform repetitive tasks and generally make their work more readable.
The examples below won’t seem very useful yet, but we wanted to expose it to the idea. You might find great use for them later.
Here’s an example (trivial) function that adds two numbers. Read the cell, then run it, then we’ll explain.
Let’s break down the pieces.
addup is the name we are giving our new function. We could have called it anything we wanted - add or banana or whatever - it’s just like a variable.
<- is the assignment operator, saying whatever comes after this is going to be saved under the label addup
function is a special keyword announcing, “I AM NOW GOING TO DEFINE A NEW FUNCTION”
(a, b) says “this function has two arguments - I’m going to refer to them as a and b in my code.” You can pick any names you want for the arguments, whatever is readable.
{ says “now the function starts. whenenver someone calls addup, run this code”
total <- a + b defines a new variable as the sum of a and b
return(total) says “this is my return value - send that back to whoever called me”
} indicates the function is over.
Below are a few other example function definitions:
Here we made the function a little more condensed. We put the math right inside the return statement. But the idea is the same.
This is a function that takes zero arguments! But we still have to write function() (empty parentheses) both in defining the function and in calling it later (sayhi())
Exercise 42
Write a function called spread that takes three arguments (all assumed to be numbers) and returns the difference between the largest and smallest number. The native R functions max and min may be helpful….
To clarify, calling spread(3, 5, 7) should return 4
Show answer
spread <- function(x, y, z) {
low = min(x, y, z)
high = max(x, y, z)
return(high - low)
}