Ranae Dietzel & Andee Kaplan
Structure:
if(condition) {
#code to run if condition is true
} else if(second condition) {
#other code to run if second true
} else {
#finally, code to run if conditions false
}
Example:
x <- "hello"
if (!is.numeric(x)) {
print("Numeric input is required")
} else {
print(TRUE)
}
## [1] "Numeric input is required"
R
offers several loops: for, while, repeat.for(i in 1:2){
print(i)
}
## [1] 1
## [1] 2
library(ggplot2)
cols <- colnames(diamonds)
for(i in cols) {
print(paste(i, ":", class(diamonds[, i])))
}
## [1] "carat : numeric"
## [1] "cut : ordered" "cut : factor"
## [1] "color : ordered" "color : factor"
## [1] "clarity : ordered" "clarity : factor"
## [1] "depth : numeric"
## [1] "table : numeric"
## [1] "price : integer"
## [1] "x : numeric"
## [1] "y : numeric"
## [1] "z : numeric"
i <- 1
while (i <= 5) {
print(i)
i <- i + 1
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
Example function
foo <- function(params) {
#code goes here
return(output)
}
Hello, world!
foo <- function(n = 10) {
stopifnot(n > 0)
for(i in 1:n){
print("Hello, world \n")
}
}
foo(3)
## [1] "Hello, world \n"
## [1] "Hello, world \n"
## [1] "Hello, world \n"