In the exercises below we cover the basics of conditional execution. In all previous exercises, the solutions required one or more R statements that were all executed consecutively. In this series of exercises we’re going to use the `if`

, `else`

and `ifelse`

functions, to execute only a subset of the R script, depending on one or more conditions. Before proceeding, first read section 9.2.1 of An Introduction to R, and the help pages for the `if`

and `ifelse`

functions.

Answers to the exercises are available here.

Many of the exercises below could be solved using standard functions, like `max`

or `abs`

. For the purpose of these exercises, however, avoid these functions and try to solve each problem using conditional execution.

**Exercise 1**

Create an R script that returns the absolute value of an integer vector `x`

of length one.

**Exercise 2**

Create an R script that calculates the square root of a given integer vector `x`

of length one, if the value contained in `x`

is negative it should return `NA`

.

**Exercise 3**

Create an R script that returns the maximum value out of the elements of a numeric vector `x`

of length 2.

**Exercise 4**

Create an R script that returns `TRUE`

if the elements of a vector `x`

, with length 3, are strictly increasing.

**Exercise 5**

Create an R script that returns the max value of a vector `x`

with length 3. Don’t use the aid of an auxiliary variable.

**Exercise 6**

Create an R script that returns the amount of values that are larger than the mean of a vector. You are allowed to use `mean()`

.

**Exercise 7**

Create an R script that, given a numeric vector `x`

with length 3, will print the elements by order from high to low.

Image by Ambigraphe (Own work) [GFDL or CC BY-SA 3.0], via Wikimedia Commons

**What's next:**

- Explore all our (>1000) R exercises
- Find an R course using our R Course Finder directory
- Subscribe to receive weekly updates and bonus sets by email
- Share with your friends and colleagues using the buttons below

## Leave a Reply