`rivers`

, `women`

and `nhtemp`

), or created them by stringing together several numbers with the `c`

function (e.g. `c(1, 2, 3, 4)`

). R offers an extremely useful shortcut to create vectors of the latter kind, which is the colon `:`

operator. Instead of having to type:
`x <- c(1, 2, 3, 4)`

we can simply type

`x <- 1:4`

to create exactly the same vector. Obviously this is especially useful for longer sequences.

In fact, you will use sequences like this a lot in real-world applications of R, e.g. to select subsets of data points, records, or variables. The exercises in this set might come across as a little abstract, but trust me, these sequences are really the basic building blocks for your future R scripts. So let’s go ahead!

Before starting the exercises, please note this is the fourth set in a series of five: In the first three sets, we practised creating vectors, vector arithmetics, and various functions. You can find all sets in our ebook Start Here To Learn R – vol. 1: Vectors, arithmetic, and regular sequences. The book also includes all solutions (carefully explained), and 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.

One more thing: I would really appreciate your feedback on these exercises: Which ones did you like? Which ones were too easy or too difficult? Please let me know what you think here!

Try to shorten the notation of the following vectors as much as possible, using `:`

notation:

`x <- c(157, 158, 159, 160, 161, 162, 163, 164)`

`x <- c(15, 16, 17, 18, 20, 21, 22, 23, 24)`

`x <- c(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)`

`x <- c(-1071, -1072, -1073, -1074, -1075, -1074, -1073, -1072, -1071)`

`x <- c(1.5, 2.5, 3.5, 4.5, 5.5)`

(Solution)

The `:`

operator can be used in more complex operations along with arithmetic operators, and variable names. Have a look at the following expressions, and write down what sequence you think they will generate. Then check with R.

`(10:20) * 2`

`105:(30 * 3)`

`10:20*2`

`1 + 1:10/10`

`2^(0:5)`

(Solution)

Use the `:`

operator and arithmetic operators/functions from the previous chapter to create the following vectors:

`x <- c(5, 10, 15, 20, 25, 30)`

`x <- c(0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3)`

`x <- c(1/5, 2/6, 3/7, 4/8, 5/9, 6/10, 7/11, 8/12)`

`x <- (1, 4, 3, 8, 5, 12, 7, 16, 9, 20)`

(Hint: you have to use the recycle rule)

(Solution)

Another way to generate a sequence is the `seq`

function. Its first two arguments are `from`

and `to`

, followed by a third, which is `by`

. `seq(from=5, to=30, by=5)`

replicates part (a) of the previous exercise.

Note that you can omit the argument names `from`

, `to`

, and `by`

, if you stick to their positions, i.e., `seq(5, 30, 5)`

. Have a look at the following expressions, and write down what sequence you think they will generate. Then check with R.

`seq(from=20, to=80, by=20)`

`seq(from=-10, to=5, by=0.5)`

`seq(from=10, to=-3, by=-2)`

`seq(from=0.01, to=0.09, by=0.02)`

(Solution)

Compare the regular sequence of exercises 2(a) and 3(a) (both using the `:`

operator) with the same sequences using the `seq`

function with appropriate `by`

argument. Can you think of a more general rule how to convert any `seq(from, to, by)`

statement to a sequence generated with the `:`

operator?

In other words, rewrite `seq(from=x, to=y, by=z)`

to a statement using the `:`

operator. Hint: if this appears difficult, try to do this first by choosing some values for `x`

, `y`

, and `z`

, and see which pattern emerges.

(Solution)

The previous exercises in this set were aimed at generating sets of *increasing* or *decreasing* numbers. However, sometimes you just want a set of *equal* numbers. You can accomplish this with the `rep`

function (from “replicate”). Its first argument is the number or vector that will be replicated, and its second argument `times`

, … well I guess you can guess that one already. Now, let’s shorten the following statements, using `rep`

:

`x <- c(5, 5, 5, 5, 5, 5, 5)`

`x <- c(5, 6, 7)`

`y <- c(x, x, x, x, x)`

`x <- (10, 16, 71, 10, 16, 71, 10, 16, 71)`

(Solution)

`rep`

has a third very useful argument: `each`

. As we saw in the previous exercise (part b), vectors are replicated in their entirety by `rep`

.

However, you can also replicate “each” individual element. Consider for example:

`seq(c(1, 2, 3), times=2, each=3)`

.

This says: “replicate each element of the input vector `c(1, 2, 3)`

3 times, and then replicate the resulting vector 2 times.” Now, let’s shorten the following statements, using `rep`

:

`x <- c(5, 5, 5, 5, 8, 8, 8, 8, -3, -3, -3, -3, 0.34, 0.34, 0.34, 0.34)`

`x <- c(-0.1, -0.1, -0.9, -0.9, -0.6, -0.6)`

`x <- c(1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3)`

(Solution)

We can actually write part c of te previous exercise even more compact by using `rep`

in combination with the `:`

operator. Do you see how?

In this exercise we’re using combinations of `rep`

, `:`

and `seq`

to create the following sequences:

`x <- c(97, 98, 99, 100, 101, 102, 97, 98, 99, 100, 101, 102, 97, 98, 99, 100, 101, 102)`

`x <- c(-5, -5, -5, -5, -6, -6, -6, -6, -7, -7, -7, -7, -8, -8, -8, -8)`

`x <- c(13, 13, 17, 17, 21, 21, 25, 25, 29, 29, 13, 13, 17, 17, 21, 21, 25, 25, 29, 29)`

`x <- c(1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0)`

(Solution)

Suppose there would be no `each`

argument for `rep`

. Rewrite the following statement, without using the `each`

argument: `x <- rep(c(27, 31, 19, 14), each=v, times=w)`

(Solution)

Let’s finish this set off with an application. Let’s create a series of vectors for later use in a timeseries dataset. The idea is that each observation in this dataset can be identified by a *timestamp*, which is defined by four vectors:

- s (for seconds)
- m (minutes)
- h (hours)
- d (days)

For this exercise, we’ll limit the series to a full week of 7 days.

This is a somewhat more complicated problem than the previous ones in this exercise. Don’t worry however! Whenever you’re faced with a somewhat more complicated problem than you are used to, the best strategy is to break it down into smaller problems. So, we’ll simply start with the `s`

vector.

- Since
`s`

counts the number of seconds, we know it has to start at 1, run to 60, restart at 1, etc. As it should cover a full week, we also know we have to replicate this series many times. Can you calculate exactly how many times it has to replicate this series? Use the outcome of your calculation to create the full`s`

vector. - Now, let’s create the vector
`m`

. Think about how this vector differs from`s`

. What does this mean for the`times`

and`each`

arguments? - Now, let’s create vector
`h`

and`d`

using the same logic. Check that`s`

,`m`

,`h`

, and`d`

have equal length.

(Solution)

- Spatial Data Analysis: Introduction to Raster Processing (Part 1)
- Spatial Data Analysis: Introduction to Raster Processing: Part-3
- Advanced Techniques With Raster Data: Part 1 – Unsupervised Classification
- Become a Top R Programmer Fast with our Individual Coaching Program
- Explore all our (>4000) R exercises
- Find an R course using our R Course Finder directory

Sofar, the functions we have practised (`log`

, `sqrt`

, `exp`

, `sin`

, `cos`

, and `acos`

) always return a vector with the same length as the input vector. In other words, the function is applied element by element to the elements of the input vector. Not all functions behave this way though. For example, the function `min(x)`

returns a single value (the minimum of all values in `x`

), regardless of whether x has length 1, 100 or 100,000.

Before starting the exercises, please note this is the third set in a series of five: In the first two sets, we practised creating vectors and vector arithmetics. In the fourth set (posted next week) we will practise regular sequences and replications.

You can find all sets right now in our ebook Start Here To Learn R – vol. 1: Vectors, arithmetic, and regular sequences. The book also includes all solutions (carefully explained), and 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.

One more thing: I would really appreciate your feedback on these exercises: Which ones did you like? Which ones were too easy or too difficult? Please let me know what you think here!

Did you know R has actually lots of built-in datasets that we can use to practise? For example, the `rivers`

data “gives the lengths (in miles) of 141 “major” rivers in North America, as compiled by the US Geological Survey” (you can find this description, and additonal information, if you enter `help(rivers)`

in R. Also, for an overview of all built-in datasets, enter `data()`

.

Have a look at the `rivers`

data by simply entering `rivers`

at the R prompt. Create a vector `v`

with 7 elements, containing the number of elements (`length`

) in `rivers`

, their sum (`sum`

), mean (`mean`

), median (`median`

), variance (`var`

), standard deviation (`sd`

), minimum (`min`

) and maximum (`max`

).

(Solution)

For many functions, we can tweak their result through additional *arguments*. For example, the `mean`

function accepts a `trim`

argument, which trims a fraction of observations from both the low and high end of the vector the function is applied to.

- What is the result of
`mean(c(-100, 0, 1, 2, 3, 6, 50, 73), trim=0.25)`

? Don’t use R, but try to infer the result from the explanation of the`trim`

argument I just gave. Then check your answer with R. - Calculate the mean of
`rivers`

after trimming the 10 highest and lowest observations. Hint: first calculate the trim fraction, using the`length`

function.

(Solution)

Some functions accept multiple vectors as inputs. For example, the `cor`

function accepts two vectors and returns their correlation coefficient. The `women`

data “gives the average heights and weights for American women aged 30-39”. It contains two vectors `height`

and `weight`

, which we access after entering `attach(women)`

(we’ll discuss the details of `attach`

in a later chapter).

- Using the
`cor`

function, show that the average height and weight of these women are almost perfectly correlated. - Calculate their covariance, using the
`cov`

function. - The
`cor`

function accepts a third argument`method`

which allows for three distinct methods (“pearson”, “kendall”, “spearman”) to calculate the correlation. Repeat part (a) of this exercise for each of these methods. Which is the method chosen by the default (i.e. without specifying the method explicitly?)

(Solution)

In the previous three exercises, we practised functions that accept one or more vectors of any length as input, but return a single value as output. We’re now returning to functions that return a vector of the same length as their input vector. Specifically, we’ll practise rounding functions. R has several functions for rounding. Let’s start with `floor`

, `ceiling`

, and `trunc`

:

`floor(x)`

rounds to the largest integer not greater than`x`

`ceiling(x)`

rounds to the smallest integer not less than`x`

`trunc(x)`

returns the integer part of`x`

To appreciate the difference between the three, I suggest you first play around a bit in R with them. Just pick any number (with or without a decimal point, positive and negative values), and see the result each of these functions gives you. Then make it somewwat closer to the next integer (either above or below), or flip the sign, and see what happens. Then continue with the following exercise:

Below you will find a series of arguments (x), and results (y), that can be obtained by choosing one *or more* of the 3 functions above (e.g. `y <- floor(x)`

). Which of the above 3 functions could have been used in each case? First, choose your answer without using R, then check with R.

`x <- c(300.99, 1.6, 583, 42.10)`

`y <- c(300, 1, 583, 42)`

`x <- c(152.34, 1940.63, 1.0001, -2.4, sqrt(26))`

`y <- c(152, 1940, 1, 5, -2)`

`x <- -c(3.2, 444.35, 1/9, 100)`

`y <- c(-3, -444, 0, -100)`

`x <- c(35.6, 670, -5.4, 3^3)`

`y <- c(36, 670, -5, 27)`

(Solution)

In addition to `trunc`

, `floor`

, and `ceiling`

, R also has `round`

and `signif`

rounding functions. The latter two accept a second argument `digits`

. In case of `round`

, this is the number of decimal places, and in case of `signif`

, the number of significant digits. As with the previous exercise, first play around a little, and see how these functions behave. Then continue with the exercise below:

Below you will find a series of arguments (x), and results (y), that can be obtained by choosing one, or both, of the 2 functions above (e.g. `y <- round(x, digits=d)`

). Which of these functions could have been used in each case, and what should the value of `d`

be? First, choose your answer without using R, then check with R.

`x <- c(35.63, 300.20, 0.39, -57.8)`

`y <- c(36, 300, 0, -58)`

`x <- c(153, 8642, 10, 39.842)`

`y <- c(153.0, 8640.0, 10.0, 39.8)`

`x <- c(3.8, 0.983, -23, 7.1)`

`y <- c(3.80, 0.98, -23.00, 7.10)`

(Solution)

Ok, let’s continue with a really interesting function: `cumsum`

. This function returns a vector of the same length as its input vector. But contrary to the previous functions, the value of an element in the output vector depends not only on its corresponding element in the input vector, but on *all previous* elements in the input vector. So, its results are *cumulative*, hence the `cum`

prefix. Take for example: `cumsum(c(0, 1, 2, 3, 4, 5))`

, which returns: 0, 1, 3, 6, 10, 15. Do you notice the pattern?

Functions that are similar in their behavior to `cumsum`

, are: `cumprod`

, `cummax`

and `cummin`

. From just their naming, you might already have an idea how they work, and I suggest you play around a bit with them in R before continuing with the exercise.

- The
`nhtemp`

data contain “the mean annual temperature in degrees Fahrenheit in New Haven, Connecticut, from 1912 to 1971”. (Although`nhtemp`

is not a vector, but a timeseries object (which we’ll learn the details of later), for the purpose of this exercise this doesn’t really matter.) Use one of the four functions above to calculate the maximum mean annual temperature in New Haven observed since 1912, for each of the years 1912-1971. - Suppose you put $1,000 in an investment fund that will exhibit the following annual returns in the next 10 years: 9% 18% 10% 7% 2% 17% -8% 5% 9% 33%. Using one of the four functions above, show how much money your investment will be worth at the end of each year for the next 10 years, assuming returns are re-invested every year. Hint: If an investment returns e.g. 4% per year, it will be worth 1.04 times as much after one year, 1.04 * 1.04 times as much after two years, 1.04 * 1.04 * 1.04 times as much after three years, etc.

(Solution)

R has several functions for sorting data: `sort`

takes a vector as input, and returns the same vector with its elements sorted in increasing order. To reverse the order, you can add a second argument: `decreasing=TRUE`

.

- Use the
`women`

data (exercise 3) and create a vector`x`

with the elements of the`height`

vector sorted in decreasing order. - Let’s look at the
`rivers`

data (exercise 1) from another perspective. Looking at the 141 data points in`rivers`

, at first glance it seems quite a lot have zero as their last digit. Let’s examine this a bit closer. Using the modulo operator you practised in exercise 9 of the previous exercise set, to isolate the last digit of the`rivers`

vector, sort the digits in increasing order, and look at the sorted vector on your screen. How many are zero? - What is the total length of the 4 largest rivers combined? Hint: Sort the rivers vector from longest to shortest, and use one of the
`cum...`

functions to show their combined length. Read off the appropriate answer from your screen.

(Solution)

Another sorting function is `rank`

, which returns the ranks of the values of a vector. Have a look at the following output:

```
x <- c(100465, -300, 67.1, 1, 1, 0)
rank(x)
```

`## [1] 6.0 1.0 5.0 3.5 3.5 2.0`

- Can you describe in your own words what
`rank`

does? - In exercise 3(c) you estimated the correlation between
`height`

and`weight`

, using Spearman’s rho statistic. Try to replicate this using the`cor`

function, without the`method`

argument (i.e., using its default Pearson method, and using`rank`

to first obtain the ranks of`height`

and`weight`

.

(Solution)

A third sorting function is `order`

. Have a look again at the vector `x`

introduced in the previous exercise, and the output of `order`

applied to this vector:

```
x <- c(100465, -300, 67.1, 1, 1, 0)
order(x)
```

`## [1] 2 6 4 5 3 1`

- Can you describe in your own words what
`order`

does? Hint: look at the output of`sort(x)`

if you run into trouble. - Remember the time series of mean annual temperature in New Haven, Connecticut, in exercise 6? Have a look at the output of
`order(nhtemp)`

:

`order(nhtemp)`

```
## [1] 6 15 29 9 13 3 5 12 7 23 1 24 47 25 51 14 18 32 16 11 56 8 17
## [24] 28 45 52 31 37 4 22 36 39 54 19 34 26 49 30 33 53 55 21 27 58 10 50
## [47] 57 59 43 44 35 2 46 48 40 20 60 41 38 42
```

Given that the starting year for this series is 1912, in which years did the lowest and highest mean annual temperature occur?

- What is the result of order(sort(x)), if x is a vector of length 100, and all of its elements are numbers? Explain your answer.

(Solution)

In exercise 1 of this set, we practised the `max`

function, followed by the `cummax`

function in exercise 6. In the final exercise of this set, we’re returning to this topic, and will practise yet another function to find a maximum. While the former two functions applied to a *single* vector, it’s also possible to find a maximum across *multiple* vectors.

- First let’s see how
`max`

deals with multiple vectors. Create two vectors`x`

and`y`

, where`x`

contains the first 5 even numbers greater than zero, and`y`

contains the first 5 uneven numbers greater than zero. Then see what`max`

does, as in`max(x, y)`

. Is there a difference with`max(y, x)`

? - Now, try
`pmax(x, y)`

, where p stands for “parallel”. Without using R, what do you think intuitively, what it will return? Then, check, and perhaps refine, your answer with R. - Now try to find the parallel minimum of x and y. Again, first try to write down the output you expect. Then check with R (I assume, you can guess the appropriate name of the function).
- Let’s move from two to three vectors. In addition to
`x`

and`y`

, add`-x`

as a third vector. Write down the expected output for the parallel minima and maxima, then check your answer with R. - Finally, let’s find out how
`pmax`

handles vectors of different lenghts Write down the expected output for the following statements, then check your answer with R.

`pmax(x, 6)`

`pmax(c(x, x), y)`

`pmin(x, c(y, y), 3)`

(Solution)

- Vectors and Functions
- Advanced Techniques With Raster Data: Part 1 – Unsupervised Classification
- Spatial Data Analysis: Introduction to Raster Processing (Part 1)
- Become a Top R Programmer Fast with our Individual Coaching Program
- Explore all our (>4000) R exercises
- Find an R course using our R Course Finder directory

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.

Let’s create the following vectors:

`u <- 4`

`v <- 8`

Use the elementary arithmetic operators `+`

, `-`

, `*`

, `/`

, and `^`

to:

- add
`u`

and`v`

- subtract
`v`

from`u`

- multiply
`u`

by`v`

- divide
`u`

by`v`

- raise
`u`

to the power of`v`

(Solution)

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:

- add
`u`

and`v`

- subtract
`v`

from`u`

- multiply
`u`

by`v`

- divide
`u`

by`v`

- raise
`u`

to the power of`v`

(Solution)

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:

- add
`u`

and`v`

- subtract
`v`

from`u`

- multiply
`u`

by`v`

- divide
`u`

by`v`

- 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)

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:

`w <- (u + 0.5 * v) ^ 2`

`w <- (u + 2) * (u - 5) + v`

`w <- (u + 2) / ((u - 5) * v)`

(Solution)

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)

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!

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.

- Suppose the surface area of a circle equals 25, what is the radius?
- 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)

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.

- 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. - 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. - Does the last value of
`n`

surprise you? Can you explain it?

(Solution)

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`

- 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). - Convert the 4 coordinates from degrees to radians, using the formula: \[radians = degrees \frac{\pi}{180}\]
- 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`

. - Finally, to find the distance, multiply \(\Delta\sigma\) (i.e., the outcome you just calculated) by the radius of the earth (6371 km.)

(Solution)

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)

May I kindly ask you to share your thoughts on these exercises? This will allow me to further improve the quality of the exercises.

You can share your thoughts simply by adding a comment below. I am particularly interested in:

- Which exercises you liked least and most
- Which (if any) exercises were too hard, and should be simplified
- Which (if any) exercises were too easy and should be more challenging
- Overall comments on the quality of this set
- Which topics you’d like to see addressed in future sets

Because vectors are such a key concept, we’re going to practise their use and application slowly, step-by-step. For now we’ll just practise *numeric* vectors (and save other types, such as *character* vectors, for later).

In this set we’re practising the basics of vectors, i.e. how to create vectors and assign them to a name. It is the first set in a series of five: In the second set (posted next week) we will practise working with vectors. In set three and four we will practise 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 our 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.

Let’s start really easy (don’t worry, we’ll quickly move to more challenging problems) with a vector containing just a single number, which we also call a scalar. Enter a vector in R, by just typing a random number, e.g. `100`

, at the prompt and hit the Enter key.

(Solution)

Great! You just created your first vector! Now, let’s first enter a vector with more than one number. E.g. a vector containing the numbers 1, 2, 3, 4, 5, in that order. If you enter these numbers just like this, R will respond with an error message. It throws an error, because it needs a little bit more information from our side that we actually want to store those numbers in a vector structure. We have to use the following notation for this:

`c(1, 2, 3, 4, 5)`

.

Now, enter a vector with the first 5 even numbers in R, and hit Enter.

(Solution)

Let’s now enter a much longer vector, containing the numbers 1 to 10, 10 times (use copy & paste). What do the numbers between square brackets in the R output mean?

(Solution)

You should be pretty familiar with entering vectors now. You might actually feel a little *bored* by typing all these numbers. Life would be pretty miserable if we would have to enter data this way over and over again in R. But fortunately, there is a neat solution! We can *assign* a vector to a variable name such that we can retrieve the data we have entered, conveniently by just typing the name of the variable.

Try to assign a vector containing the numbers 1, 2, 3, 4, 5 to a variable named `a`

, using the assignment operator (`<-`

), and see which of the statements below work.

Enter each of the 9 statements one at a time at the prompt, hit Enter, and try to retrieve the contents of `a`

, by typing `a`

at the prompt after you entered each statement:

`a<-c(1, 2, 3, 4, 5)`

`a <- c(50, 60, 70, 80, 90)`

`a -> c(20, 31, 42, 53, 64)`

`c(5, 6, 7, 9, 10) <- a`

`c(101, 102, 103, 104, 105) -> a`

`a < - c(11, 12, 13, 14, 15)`

`a < -c(100, 99, 88, 77, 66)`

`assign(a, c(1000, 2000, 3000, 4000, 5000))`

`assign('a', c(83, 16, 35, 58, 3))`

(Solution)

In an R script, you might have created dozens or even hundreds of vectors. In that case, naming them `a`

, `b`

, `c`

etc. is not ideal, because it will be difficult to keep track of what all those letters actually mean. This problem is easily mitigated by using longer, and meaningful, variable names.

Assign the following vectors to a meaningful variable name:

`c(2, 4, 6, 8, 10, 12, 14, 16, 20)`

`0`

`3.141593`

`c(1, 10, 100, 1000, 10000, 100000)`

(Solution)

Create vectors that correspond to the following variables names:

- bmi
- age
- daysPerMonth
- firstFivePrimeNumbers

(Solution)

So far, we have created vectors from a bunch of numbers. Instead of numbers, however, you can also enter other vectors, e.g. `c(vector1, vector2, vector3)`

, and string them together.

To practise this, let’s first create three vectors that each contain just 1 element with variable names `p`

, `q`

, and `r`

, and values 1, 2, and 3. Then, create a new vector that contains multiple elements, using the scalars we just created. I.e., create a vector `u`

of length 3, with the subsequent elements of `p`

, `q`

and `r`

.

(Solution)

To play with this a little more, let’s create a longer vector, using only the assignment operator (`<-`

), the `c()`

function, and the vector `u`

we just created. I.e., create a new vector `u`

with length 96 that contains the elements of `u`

as follows: 1, 2, 3, 1, 2, 3, …., 1, 2, 3

(Solution)

May I kindly ask you to share your thoughts on these exercises? This will allow me to further improve the quality of the exercises.

You can share your thoughts simply by adding a comment below. I am particularly interested in:

- Which exercises you liked least and most
- Which (if any) exercises were too hard, and should be simplified
- Which (if any) exercises were too easy and should be more challenging
- Overall comments on the quality of this set
- Which topics you’d like to see addressed in future sets

- Mathematical Expressions in R Plots: Tutorial
- Spatial Data Analysis: Introduction to Raster Processing (Part 1)
- Parallel Computing Exercises: Foreach and DoParallel (Part-2)
- Become a Top R Programmer Fast with our Individual Coaching Program
- Explore all our (>4000) R exercises
- Find an R course using our R Course Finder directory

`paste()`

), they are often not using it enough in their own functions. In other cases, the ellipsis is just not used properly or not fully taken advantage of. In this tutorial we will go through some common mistakes in using the ellipsis feature, and some interesting options to fully utilize it and the flexibility that it offers.
**Choose lists over vectors**

The most common mistake is trying to assign the ellipsis content to a vector rather than a list. Well, of course it’s not so much of a mistake if we’re expecting only a single data type from the ellipsis arguments, but this is often not the case and assigning the arguments to a vector rather than a list might cause problems when there’s a variety of data types.

So make sure you’re always unpacking the ellipsis content using the `list()`

function rather than the `c()`

function. As an example, try running this piece of code with both options:

my_ellipsis_function <- function(...) {

args <- list(...) # good

# args <- c(...) # bad

length(args)

}

my_ellipsis_function(“Hello World”, mtcars)

**Combine the ellipsis with other arguments**

Some tend to think that it’s not possible to use the ellipsis with other regular arguments. This is not the case, and the ellipsis-arguments shouldn’t be the only ones in your function. You can combine them with as many regular arguments as you wish.

my_ellipsis_function <- function(x, ...) {

print(paste("Class of regular-argument:", class(x)))

print(paste("Number of ellipsis-arguments:", length(list(...))))

}

my_ellipsis_function(x = “Hello World”, mtcars, c(1:10), list(“Abc”, 123))

**Don’t forget the names**

In fact, the values of the arguments themselves are not the only information that is passed through the ellipsis-arguments. The names of the arguments (if specified) can also be used. For example:

my_ellipsis_function <- function(...) {

names(list(...))

}

my_ellipsis_function(some_number = 123, some_string = “abc”, some_missing_value = NA)

Lastly, somewhat of an advanced procedure might be unpacking the ellipsis-arguments into local function variables (or even global). There are all kind of scenarios where it might be needed (for global variables assignment it might be more intuitive). One example for a need in local variables, is where a certain function takes a certain regular-argument, that is dependent on a varying set of other variables. A use of the function glue::glue() within another function is a good example for that. The following code demonstrates how simple it is to perform this “unpacking”:

my_ellipsis_function <- function(...) {

args <- list(...)

for(i in 1:length(args)) {

assign(x = names(args)[i], value = args[[i]])

}

ls() # show the available variables

# some other code and operations

# that use the ellipsis-arguments as “native” variables…

}

my_ellipsis_function(some_number = 123, some_string = “abc”)

So whether you’re an R beginners or not, don’t forget to utilize this convenient feature when needed, and use it wisely.

]]>- Building Shiny App exercises part 3
- Parallel Computing Exercises: Foreach and DoParallel (Part-2)
- Parallel Computing Exercises: Snow and Rmpi (Part-3)
- Become a Top R Programmer Fast with our Individual Coaching Program
- Explore all our (>4000) R exercises
- Find an R course using our R Course Finder directory

The biggest advantage of modules is the ability to efficiently reuse Shiny code, which can save a great deal of time. In addition, modules can help you standardize and scale your Shiny operations. Lastly, even if not reused, Shiny modules can help with organizing the code and break it into smaller pieces – which is very much needed in many complex Shiny apps. Some more information on Shiny modules can be found here.

In the following exercise set, you will practice the not-so-straightforward use of Shiny modules. The first four exercises are a warm-up, and will help you “refresh” on how to build each part of a Shiny module. In each of the last six exercises you will build a complete end-to-end module and run a minimal Shiny app to test it. Answers to the exercises are available here.

Two reminders before we begin:

* A typical UI function would take the argument `id`

and start with the line `ns <- NS(id)`

.

* All input and output IDs within a UI function should be wrapped with the function like `ns()`

.

**Exercise 1**

Build a module-UI-function that provides a `selectInput`

control, where the choices are `LETTERS`

.

**Exercise 2**

Build the corresponding module-server-function, that prints the selected letter to the console.

**Exercise 3**

Build a regular UI object that contains the module-UI-function.

**Exercise 4**

Build a regular server function that calls the module you built in exercises 1 and 2.

Put together a minimal Shiny app that runs everything (e.g, `shinyApp(ui = ui, server = server)`

).

**Exercise 5**

Adjust the module you built to show the selecter letter as a UI `textOutput`

instead of printing it to the console.

**Exercise 6**

In some cases you’ll need the same module twice in a single Shiny app.

Build a minimal Shiny app that uses the module from exercise 5 twice.

**Exercise 7**

Still with the same “letters” module, add an option for the app developer to select the label of the `selectInput`

, with the default value being “Select a letter”. Call the module with a different value for the label than the default.

**Exercise 8**

Build a “contact form” module that contains a name (`textInput`

), a subject (`selectInput`

with dynamic choices, namely the person who uses the module can choose which choices to display) a message (`textAreaInput`

) and a button (`actionButton`

with a dynamic label). Upon clicking the button, all of the form information should be saved in a text file.

**Exercise 9**

Build a module that takes a number *n* using `numericInput`

, and generates *n* elements of type `textInput`

.

**Exercise 10**

Modules can also be nested within each other. Namely, one module can call anther module.

To practice that, create two modules, an “inner” one and an “outer” one.

Your minimal Shiny app should call the “outer” module, that in turn will call the “inner” module.

The module-server-functions should take an argument `text`

, and render it as a `textOutput`

.

- Parallel Computing Exercises: Foreach and DoParallel (Part-2)
- Parallel Computing Exercises: Snow and Rmpi (Part-3)
- Bayesian Inference – MCMC Diagnostics using coda : Exercises
- Become a Top R Programmer Fast with our Individual Coaching Program
- Explore all our (>4000) R exercises
- Find an R course using our R Course Finder directory

Even though the DT package can be used independently of Shiny, this exercise set will focus on the integration between the two packages. The exercises were built with a practical orientation in mind, and upon completing them you would be ready to tackle the vast majority of use cases for using DT with Shiny.

We will work with the light built-in dataset `datasets::Orange`

, that holds data about growth of orange trees. Each exercise is adding some more features/functionalities to the code of the previous exercise, so be sure to not discard the code until after you’re done with all of the exercises. Answers to the exercises are available here.

Each exercises should result in a Shiny app, where the changing part is the `renderDataTable()`

function.

To save time, you can use the following template, and just replace the placeholder for each exercise.

ui <- fluidPage(

br(), br(), br(),

fluidRow(column(width = 6, DT::dataTableOutput(outputId = "my_datatable")))

)

server <- function(input, output, session) {

output$my_datatable <-

}

shinyApp(ui = ui, server = server)

**Exercise 1**

Generate a minimal Shiny app that displays the dataset `Orange`

in a datatable (default values).

**Exercise 2**

Remove the row names.

**Exercise 3**

Show only 7 rows as the default display, and allow changing the number of displayed rows to either 14, 21, 28 or 35.

**Exercise 4**

Align the columns text (both values and headers) to the center.

**Exercise 5**

Remove the search box (top right) and the table information text (bottom left).

**Exercise 6**

Add a “copy” and “csv” buttons to allow saving the table to the clipboard and downloading it as a CSV respectively.

**Exercise 7**

Add a filter box for each column, at the bottom of the table.

**Exercise 8**

Allow selection of a single row only, rather than multiple rows (which is the default).

**Exercise 9**

Remove the option to sort the table.

**Exercise 10**

Finally, if a row was selected, display in the UI (`textOutput`

) the selected `tree`

and `age`

values.

Hint: for this exercise you would have to make additional changes to the UI and server, rather than just changing the `renderDataTable()`

function.

- Bayesian Inference – MCMC Diagnostics using coda : Exercises
- Practice Your ggplot Skills: Exercises
- Parallel Computing Exercises: Snow and Rmpi (Part-3)
- Become a Top R Programmer Fast with our Individual Coaching Program
- Explore all our (>4000) R exercises
- Find an R course using our R Course Finder directory

With a simple and consistent syntax, stringr provides some very convenient functions around pattern matching, characters manipulation, whitespace handling and more. The full reference of the package can be found here.

Please find below a set of exercises that will help you practice a variety of stringr functions. The focus is on practical operations that data analysts are required to perform on a daily basis. Answers to the exercises are available here. And, don’t forget to check out our other exercise sets on the stringr package by following the stringr tag.

For the following exercises we will use this data:

addresses <- c("14 Pine Street, Los Angeles", "152 Redwood Street, Seattle", "8 Washington Boulevard, New York")

products <- c(“TV “, ” laptop”, “portable charger”, “Wireless Keybord”, ” HeadPhones “)

long_sentences <- stringr::sentences[1:10]

field_names <- c(“order_number”, “order_date”, “customer_email”, “product_title”, “amount”)

employee_skills <- c(“John Bale (Beginner)”, “Rita Murphy (Pro)”, “Chris White (Pro)”, “Sarah Reid (Medium)”)

**Exercise 1**

Normalize the `addresses`

vector by replacing capitalized letters with lower-case ones.

**Exercise 2**

Pull only the numeric part of the `addresses`

vector.

**Exercise 3**

Split the `addresses`

vector into two parts: address and city. The result should be a matrix.

**Exercise 4**

Now try to split the `addresses`

vector into three parts: house number, street and city. The result should be a matrix.

Hint: use a regex lookbehind assertion

**Exercise 5**

In the `long_sentences`

vector, for sentences that start with the letter “T” or end with the letter “s”, show the first or last word respectively. If the sentence both starts with a “T” and ends with an “s”, show both the first and the last words. Remember that the actual last character of a sentence is usually a period.

**Exercise 6**

Show only the first 20 characters of all sentences in the `long_sentences`

vector. To indicate that you removed some characters, use two consecutive periods at the end of each sentence.

**Exercise 7**

Normalize the `products`

vector by removing all unnecessary whitespaces (both from the start, the end and the middle), and by capitalizing all letters.

**Exercise 8**

Prepare the `field_names`

for display, by replacing all of the underscore symbols with spaces, and by converting it to the title-case.

**Exercise 9**

Align all of the `field_names`

to be with equal length, by adding whitespaces to the beginning of the relevant strings.

**Exercise 10**

In the `employee_skills`

vector, look for employees that are defined as “Pro” or “Medium”. Your output should be a matrix that have the employee name in the first column, and the skill level (without parenthesis) in the second column. Employees that are not qualified should get missing values in both columns.

- Mathematical Expressions in R Plots: Tutorial
- Spatial Data Analysis: Introduction to Raster Processing (Part 1)
- Parallel Computing Exercises: Foreach and DoParallel (Part-2)
- Become a Top R Programmer Fast with our Individual Coaching Program
- Explore all our (>4000) R exercises
- Find an R course using our R Course Finder directory

By the end of this tutorial, you will have the basic knowledge of how to execute operations (including R scripts) from Windows Command Prompts using a single line of code – running complex R scripts, embedding parameters within them and scheduling processes to run repeatedly.

Running R scripts from the command line can have a couple of advantages, such as automating repeating R operations, scaling a large number of R-related processes and simplifying the execution of R scripts. In some cases, you might want a server to run your R script every X hours and in other cases, it might be just more convenient to run an existing script without the need to access R or RStudio.

**Preparations**

First, we need to add a specific path as an environment variable in our system.

1. Go to Windows “Search”

2. Type “Edit the system environment variables”

3. Click the button “Environment Variables” (at the bottom)

4. On the bottom pane, under “System variables”, highlight the “Path” variable and click “Edit”.

5. Click “New” and add the path of the “bin” folder of your R software. The path usually looks like: *C:\Program Files\R\R-3.4.4\bin\* (it might change a bit between computers or R versions)

6. Click OK in all windows

Notes: Steps 1 and 2 can also be replaced with accessing “Control Panel” -> “System” -> “Advanced”.

**Start an R session**

Now we are ready to start running scripts from Windows Command Prompt!

Go to Windows “Search” again and type “Command Prompt”.

To run an R session from the command line, simply type: `R`

If you get the usual R starting message (“R is a free software…”), you’ve done everything right and you can quit the R console for now using the function `q(save = "no")`

If not, you might have missed something so please go back to the **Preparations** section. If you’re sure you’ve done everything properly and it’s still not working for you, please contact the author of this tutorial.

Now, to run a simple R script from the command line, all you have to do is type:

`Rscript path\to\the\script.R`

Try it out with a script of your choice!

**Pass parameters to your script**

To run a script with parameters, you would have to add some code to your R script that will “unpack” the parameters for the script to use. This is how it is done:

params <- commandArgs(trailingOnly = TRUE) # notice that params will be a character vector

first_param <- params[1]

second_param <- params[2]

# n_param <- params[n] …

print(first_param)

print(second_param)

Now, when you run the script from the command line, you should simply specify the parameters after the path to the script, separated by spaces:

`Rscript path\to\the\script.R value_for_the_first_parameter value_for_the_second_parameter`

**Automate processes by scheduling tasks that run R scripts**

The Windows equivalent of the famous cron utility is called “Schtasks”.

The basic syntax for scheduling a task is as follows:

`schtasks /create /sc <ScheduleType> /mo <Modifier> /tn <TaskName> /tr <TaskRun>`

1. `<ScheduleType>`

can take values like minute, hourly, daily, weekly.

2. `<Modifier>`

can take numerical values to determine the frequency of the task.

3. `<TaskName>`

is simply a string that specifies the name of the task.

4. `<TaskRun>`

is the actual command line code to run repeatedly.

So an R script task will often look like that (this code should go in the command line of course):

`schtasks /create /sc minute /mo 30 /tn "My First R Task" /tr "Rscript path\to\the\script.R"`

`schtasks /create /sc daily /mo 1 /tn "My Second R Task" /tr "Rscript path\to\the\script_2.R"`

To delete a task, use the following:

`schtasks /delete /tn "My First R Script"`

For more advanced scheduling options, check the full documentation here.

]]>- Spatial Data Analysis: Introduction to Raster Processing (Part 1)
- Mathematical Expressions in R Plots: Tutorial
- Parallel Computing Exercises: Snow and Rmpi (Part-3)
- Become a Top R Programmer Fast with our Individual Coaching Program
- Explore all our (>4000) R exercises
- Find an R course using our R Course Finder directory

This exercise set will help you practice all of the main features of this great package. By completing the two parts of the exercise series, you’ll know that you’re ready to start building well-designed Shiny apps. We will make some minimal use of the built-in data-set `datasets::CO2`

.(Specific descriptions of the data-set are irrelevant, but you can check them out by typing `?datasets::CO2`

.) Each exercise is adding some more features/functionalities to the code of the previous exercise, so be sure to not discard the code until after you’re done with all of the exercises. Answers to these exercises are available here.

In the solutions page, you’ll first find only the relevant component of each exercise. Then, at the end of the page, you will find the entire Shiny app code that contains all of the different components together. This exercise set is based on the output code of this exercise set. If you haven’t done it, you can just use the code under “All Exercises Combined” here (at the bottom) as your basis for this exercise set.

For other parts of the series, follow the tag shinydashboard.

**Exercise 1**

In the “data” tab, add a `box()`

with the title “CO2 Data.”

The box should have a blue header and it should be collapsible.

**Exercise 2**

Add the `CO2`

table to the box you just created.

The table should be filtered by the `plant`

input that was created in the previous exercise set.

**Exercise 3**

In the “licenses” tab, add a `tabBox()`

that contains two panels: one titled “Data” and one titled “Icons.”

You can leave those panels empty for now.

**Exercise 4**

In the “contact_us” tab, add an `infoBox()`

with some content of your choice and select its color and icon.

**Exercise 5**

In the “contact_us” tab, add an `valueBox()`

with some content of your choice, and select its color and icon.

**Exercise 6**

Add a “messages” drop down menu to the header.

Select its icon and badge-status and add one `messageItem()`

to it.

**Exercise 7**

Add a “tasks” drop down menu to the header.

Select its icon and badge-status and add two `taskItem()`

s to it.

**Exercise 8**

Add a placeholder for a “notifications” drop down menu in the header using `dropdownMenuOutput()`

.

The output ID should be “notifications.”

**Exercise 9**

Add the server-side code of the “notifications” drop down menu.

It should have a single notification item that shows what the current value of the `plant`

input that was created in the previous exercise set is.

**Exercise 10**

Add a link to “r-exercises.com” in the header.

Hint: use `tags$li(class = "dropdown", ...)`

together with `tags$a(...)`

.