CDE
This commit is contained in:
parent
518da4a923
commit
764da6cbbb
6144 changed files with 83610 additions and 11 deletions
13
Task/Conditional-structures/R/conditional-structures-1.r
Normal file
13
Task/Conditional-structures/R/conditional-structures-1.r
Normal 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.
|
||||
3
Task/Conditional-structures/R/conditional-structures-2.r
Normal file
3
Task/Conditional-structures/R/conditional-structures-2.r
Normal 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)
|
||||
12
Task/Conditional-structures/R/conditional-structures-3.r
Normal file
12
Task/Conditional-structures/R/conditional-structures-3.r
Normal 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.
|
||||
Loading…
Add table
Add a link
Reference in a new issue