Conditional execution exercises

January 26, 2016

[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.

conditional executionIn 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.

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

To leave a comment for the author, please follow the link and comment on their blog: R-exercises. offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)