This commit is contained in:
Ingy döt Net 2013-04-10 16:57:12 -07:00
parent 518da4a923
commit 764da6cbbb
6144 changed files with 83610 additions and 11 deletions

View file

@ -0,0 +1,13 @@
#Single line example
#x is assumed to be scalar
if(x < 3) message("x is less than 3") else if(x < 5) message("x is greater than or equal to 3 but less than 5") else message("x is greater than or equal to 5")
#Block example
if(x < 3)
{
x <- 3
warning("x has been increased to 3")
} else
{
y <- x^2
}
#It is important that the else keyword appears on the same line as the closing '}' of the if block.

View file

@ -0,0 +1,3 @@
#ifelse is a vectorised version of the if/else flow controllers, similar to the C-style ternary operator.
x <- sample(1:10, 10)
ifelse(x > 5, x^2, 0)

View file

@ -0,0 +1,12 @@
# Character input
calories <- function(food) switch(food, apple=47, pizza=1500, stop("food not known"))
calories("apple") # 47
calories("banana") # throws an error
# Numeric input
alphabet <- function(number) switch(number, "a", "ab", "abc")
alphabet(0) # null response
alphabet(1) # "a"
alphabet(2) # "ab"
alphabet(3) # "abc"
alphabet(4) # null response
# Note that no 'otherwise' option is allowed when the input is numeric.