Lecture 02b Practice

These activities are for practice only β€” there is nothing to turn in. Answer keys are included, so try each question yourself before opening them.

Question 1

Which of the following commands do you think will create an error in R? Why?

  1. score@T1 <- 3.2
  2. score_at_T1 <- 3.2
  3. score at T1 <- 3.2
  4. 1_score <- 3.2
  5. ScoreAtTime1 <- 3.2

Make your best guesses just by looking at the commands and then check your guesses by running the commands in R. Bonus: Can you come up with a better name for this variable?

Answer Key

Code Result (reason)
score@T1 <- 3.2 πŸ›‘ Error (@ not allowed in name)
score_at_T1 <- 3.2 βœ… No Error
score at T1 <- 3.2 πŸ›‘ Error (spaces not allowed in name)
1_score <- 3.2 πŸ›‘ Error (name can’t start with a number)
ScoreAtTime1 <- 3.2 βœ… No Error

Question 2

  1. Use the cos() function to calculate the cosine of 3 and assign it to a variable called y. Print the value of y to the console.
  2. Use a function to round y to the nearest whole number.
  3. Use a function to round y to two decimal places.

Answer Key

# Part (a)
y <- cos(3)
y
## [1] -0.9899925

# Part (b)
round(y)
## [1] -1

# Part (c)
round(y, digits = 2)
## [1] -0.99

Question 3

What do you expect the result to be for the following commands?

  1. sqrt(4 + 5)
  2. sqrt(4) + 5

Make your best guesses just by looking at the commands and then check your guesses by running the commands in R.

Answer Key

# Part (a): Add then square root, same as sqrt(9)
sqrt(4 + 5)
## [1] 3

# Part (b): Square root then add, same as 2 + 5
sqrt(4) + 5 
## [1] 7

Question 4

Imagine that you ran a stand selling bananas for three days. On the first day, you sold $30 worth of bananas and spent $15 on supplies. On the second day, you sold $50 worth of bananas and spent $15 on supplies. On the third day, you sold $40 worth of bananas and spent $100 on repairs to the stand (due to an unfortunate fire).

  1. Create two vectors named sales and costs to store how much you sold and how much you spent on each day, respectively.

  2. Subtract the costs object from the sales object and save the result to a new object named profits. Print this to see your profits per day.

  3. Use the sum() function to calculate your total profits over all three days. Was your effort fruitful, i.e., did you make money overall?

Answer Key

# Part (a)
sales <- c(30, 50, 40)
costs <- c(15, 15, 100)

# Part (b)
profits <- sales - costs
profits
## [1]  15  35 -60

# Part (c): No, I lost money!
sum(profits)
## [1] -10


Note that there is no need to turn in Activities. These are just for practice!