Most programming languages allow one to do one or more things when a certain condition is satisfied and something else when it is not. R is no exception. There are a couple of ways one can do this in R. The simplest is the "if
" statement, which has the following form:
if (some.condition) { one.thing.to.do second.thing.to.do third.thing.to.do # <-- you can do one or many things... }
In the above, the things in between the {} are executed only when some.condition
is TRUE
. If some.condition
is FALSE
, nothing happens.
As an explicit example, the function below prints the strings "even" and "steven" if n
is even, and nothing otherwise. (Recall, a %% b
returns the remainder of a
divided by b
)
isItEven = function(n) { if (n %% 2 == 0) { print("even") print("steven") } }
Alternatively, if one wanted to take different actions if the condition was not satisfied, an "if-else" statement is more appropriate. The structure of this statement is shown below:
if (condition) { thing1.to.do.if.condition.is.true thing2.to.do.if.condition.is.true # <-- here too, do 1 or many things } else { thing1.to.do.if.condition.is.false thing2.to.do.if.condition.is.false thing3.to.do.if.condition.is.false # <-- again, do 1 or many things here }
Suppose we roll a die and if the result is greater than 3, we "win", and if not, we "lose". The following function could model this situation:
game = function() { if (sample(1:6,size=1)>3) { print("win") } else { print("lose") } }
You can also "nest" if-statements. This is a bit like asking "follow-up questions". For example, suppose you want to print the word corresponding to the remainder of a number upon division by 3:
remainder.upon.division.by.three = function(n) { if (n %% 3 == 0) { print("zero") } else if (n %% 3 == 1) { print("one") } else { print("two") } }
There is also a function that will look at some condition and return one value if the condition is true, and another if the condition is false. (This is very similar to the IF() function in Excel), namely:
ifelse(test, yes, no)
Here, test
is the condition (something that evaluates to TRUE
or FALSE
, and yes
and no
are values that should be returned if the condition test
is TEST
or FALSE
, respectively. (Note that test
can be a vector, in which case the output will be a vector.)
Here's another way to simulate the game where one rolls a die and wins if and only if the roll is greater than 3 using this ifelse()
function:
game = function() { print(ifelse(sample(1:6,1)>3, "win", "lose")) }
As an extra little bit of awesomeness by R, note that you can also replace the no
with multiple lines of code within $\{\}$ provided the last line is the value of no
.