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
R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...