Here are my solutions to R Worksheet 1. These aren’t necessarily the only ways to solve these problems.
Remember that you can get R help at the R Practicals in Weeks 2 and 3.
Exercise 1.1. Type
2 + 3into the console next to the arrow, and then press Enter. What happens?
Let’s try!
2 + 3We see the answer [1] 5. First, the [1]
just tells us that what follows is the first part of the answer – since
our answer here only has one part, we can ignore this. (It is useful
when the answer is a very long vector or a table of values.) Then the
5 is the answer we want.
Exercise 1.2. Calculate:
(a) \(943 - 242\),
(b) \(29 \times 31\),
(c) \(2^{8+5}\),
(d) \(\displaystyle \frac{19 + 21}{5 \times 3}\).
We calculate these as follows:
943 - 242## [1] 70129 * 31## [1] 8992^(8 + 5)## [1] 8192(19 + 21) / (5 * 3)## [1] 2.666667Exercise 1.3. Use R to find:
(a) \(\frac{1}{7}\) to 4 decimal places;
(b) \(\log(10)\) to 3 significant figures;
(c) \(\sqrt{712 + 34}\) to the nearest integer.
We can find these as follows:
round(1 / 7, digits = 4)## [1] 0.1429signif(log(10), digits = 3)## [1] 2.3round(sqrt(712 + 34))## [1] 27Exercise 1.4. Create an object called
john, and assign it the value 7. Then create an object calledpauland assign it the value \(12^2\). Then get R to tell you the value ofpaulmultiplied by the value ofjohn.
We do this as follows:
john <- 7
paul <- 12^2
paul * john## [1] 1008Exercise 1.5. This exercise continues with the objects assigned in Exercise 1.4.
(a) Assign the value ofpaulmutiplied byjohnto the new valueringo.
(b) Check the value ofringo.
(c) Double the value ofringo, keeping it still stored asringo.
(d) Add 7 to the value ofringo.
(e) Check the new value ofringo. (It should be 2023.)
We do this as follows:
ringo <- paul * john
ringo## [1] 1008ringo <- 2* ringo
ringo <- ringo + 7
ringo## [1] 2023The answer is indeed 2023, as it should be.
Exercise 1.6. Write down the commands you used to solve Exercises 1.4 and 1.5 in a new R Script. Save your work with a explanatory filename that will allow you to find it again later.
Exercise 1.7. Continuing with your R Script from Exercise 1.6, add comments to make it clear which commands are doing what, then re-save your R Script.
My R Script R1-solutions.R looked like this:
# MATH1710: R WORKSHEET 1
# MY SOLUTIONS
# Last updated: 9 October 2023
# Exercise 1.1
2 + 3  # Gets output "[1] 5", meaning the answer is 5
# Exercise 1.2
943 - 242
29 * 31
2^(8 + 5)
(19 + 21) / (5 * 3)
# Exercise 1.3
round(1 / 7, digits = 4)
signif(log(10), digits = 3)
round(sqrt(712 + 34))
# Exercise 1.4
john <- 7
paul <- 12^2
paul * john
# Exercise 1.5
ringo <- paul * john
ringo
ringo <- 2* ringo
ringo <- ringo + 7
ringo  # Answer is 2023, as it should be
# Exercise 1.5 created this R Script
# Exercise 1.6 added comments to this R Script