Site icon R-bloggers

Conditional execution exercises

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

R-bloggers.com 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.