[This article was first published on R-exercises, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

In the previous exercise set we practised vectors as a data structure. As I noted at the beginning of that set, perhaps you were already familiar with data in a vector-like structure in other applications such as Microsoft Excel or SPSS. If so, perhaps you also used those data to carry out calculations. In this set, we’re going to practise all sorts of calculations with vectors, from basic operations like addition and multiplication to somewhat more advanced arithmetics.

This is the second set in a series of five: In the first set (posted last week) we practised the basics of vectors. In set three and four (upcoming) we will practise more vector arithmetics to e.g. calculate all kinds of statistics, carry out simulations, sort data, or calculate the distance between two cities.

If you can’t wait till all sets are posted: you can find them right now in my ebook Start Here To Learn R – vol. 1: Vectors, arithmetic, and regular sequences. The book also includes the fifth and final set of the series. This final set focuses on the application of the concepts you learned in the first four sets, to real-world data.

### Exercise 1

Let’s create the following vectors:

u <- 4

v <- 8

Use the elementary arithmetic operators +, -, *, /, and ^ to:

1. add u and v
2. subtract v from u
3. multiply u by v
4. divide u by v
5. raise u to the power of v

(Solution)

### Exercise 2

Now, suppose u and v are not scalars, but vectors with multiple elements:

u <- c(4, 5, 6)

v <- c(1, 2, 3)

Without using R, write down what you expect as the result of the same operations as in the previous exercise:

1. add u and v
2. subtract v from u
3. multiply u by v
4. divide u by v
5. raise u to the power of v

(Solution)

### Exercise 3

We just saw how arithmetic operators work on vectors with the same length. But how about vectors that differ in length? Let’s find out… Consider the following vectors:

u <- c(5, 6, 7, 8)

v <- c(2, 3, 4)

Without using R, write down what you expect as the result of the same operations as in the previous exercise:

1. add u and v
2. subtract v from u
3. multiply u by v
4. divide u by v
5. raise u to the power of v

Then check your answer with R. Which rule does R use, when it has to deal with vectors of different lengths?

(Solution)

### Exercise 4

When we want to carry out a series of arithmetic operations, we can either use a single expression, or a series of expressions. Consider two vectors u and v:

u <- c(8, 9, 10)

v <- c(1, 2, 3)

We can create a new vector w in a single line of code:

w <- (2 * u + v) / 10

or carry out each operation on a separate line:

w <- 2 * u

w <- w + v

w <- w / 10

Convert the following expressions to separate operations, and check that both approaches give the same result:

1. w <- (u + 0.5 * v) ^ 2
2. w <- (u + 2) * (u - 5) + v
3. w <- (u + 2) / ((u - 5) * v)

(Solution)

### Exercise 5

We can do the reverse as well. Convert the following multi-line operations to a single expression. Check that both approaches give the same result.

Part a:

w <- u + v

w <- w / 2

w <- w + u

Part b:

w1 <- u^3

w2 <- u - v

w <- w1 / w2

(Solution)

### Intro to Exercise 6, 7 and 8

Exercise 6, 7, and 8 focus on mathematics. Sooner or later you might have to translate mathematical formulas into R, to perform simple or more elaborate mathematical calculations. The goal of these exercises is to practise just that: how to translate a mathematical expression to R code. So, we won’t delve into the mathematics behind these formulas, and their derivation.

Also, in some cases, these formulas have already been translated to R by others, and are available in so-called contributed packages. We will deal with using these packages at a later stage, and for now the goal is just to become familiar with implementing mathematical formulas in R yourself.

So, here’s the deal: If you really hate math, or know for sure you will never use math in R, then it’s ok to skip exercise 6, 7, and 8. Otherwise: Let’s go for it and enjoy!

### Exercise 6

Besides the arithmetic operators we have used so far, there are some more that we often use: log, exp, and sqrt. We can also use the well-known constant pi, by simply typing pi, instead of its value 3.1415927.

Let’s try to apply what we have learned so far to some well-known, somewhat more advanced formulas. Don’t let the math scare you. Just translate the formulas to R code, one operator at a time. Don’t hesitate to use multiple lines if that makes things easier, or add parentheses to make sure operations are carried out in the right order.

1. Suppose the surface area of a circle equals 25, what is the radius?
2. What is the probability density at x=0 of a normally distributed random variable x with mean (mu) equal to zero, and standard devation (sigma) equal to one (look up the formula online, e.g. https://en.wikipedia.org/wiki/Normal_distribution)?

(Solution)

### Exercise 7

Consider the following formula to calculate the number of mortgage payment terms: $n=\frac{\ln \Bigg(\dfrac{i}{\dfrac{M}{P}-i}+1\Bigg)}{\ln(1+i)}$ In this equation, M represents the monthly payment amount, P the principle, and i the (monthly) interest rate.

1. Calculate the number of payment terms n for a mortgage with a principle balance of 200,000, monthly interest rate of 0.5%, and monthly payment amount of 2000.
2. Now construct a vector n of length 6 with the results of this calculation for a series of monthly payment amounts: 2000, 1800, 1600, 1400, 1200, 1000.
3. Does the last value of n surprise you? Can you explain it?

(Solution)

### Exercise 8

Suppose you have geographical data and want to calculate the distance between two places on earth, given by their latitude and longitude coordinates. Consider the coordinates for:

• Paris: 48.8566° N (latitude), 2.3522° E (longitude), and
• New York 40.7128° N (latitude), 74.0060° W (longitude)

If you’re up for a real challenge, lookup “Great-circle distance” on Wikipedia, and use the spherical law of cosines to find the distance (and stop reading right now!).

If this sounds like a pretty daunting task, don’t worry! I will walk you through this step-by-step in the remainder of this exercise.

Ok, here we go. We will use the following common abbreviations:

• latitude ($$\phi$$) phi
• longitude ($$\lambda$$) lambda
1. Create 4 scalars phi.paris, phi.ny, lambda.paris, lambda.ny, representing these coordinates. Because New York is located in the West, you have to enter this as a negative value (-74.0060).
2. Convert the 4 coordinates from degrees to radians, using the formula: $radians = degrees \frac{\pi}{180}$
3. Calculate the central angle between both cities, using the spherical law of cosines: $\Delta\sigma=\arccos(\sin \phi_1 \sin \phi_2 + \cos \phi_1 \cos \phi_2 \cos(\Delta\lambda))$ where: $$\Delta\sigma$$ is just a scalar (name it anything you want in R), $$\phi_1$$ is the latitude of Paris, $$\phi_2$$ the latitude of New York, and $$\Delta\lambda$$ the absolute difference between both longitudes.Hint: For this calculation you need the following mathematical functions in R: sin, cos, acos, and abs.
4. Finally, to find the distance, multiply $$\Delta\sigma$$ (i.e., the outcome you just calculated) by the radius of the earth (6371 km.)

(Solution)

### Exercise 9

Use the modulo operator (%%) to find out for which of the following pairs, the second number is a multiple of the first. Your R code should contain the modulo operator just once!

530, 1429410

77, 13960

231, 2425

8, 391600

(Solution)