if
- else
conditionsif(cond) {true.expr} else {false.expr}
cond
is TRUE
then run {true.expr}
else run {false.expr}
.if (4 < 6){
val <- 4
} else {
val <- 4 + 2
}
val
[1] 4
hello <- function(name){
words <- paste("Hello", name)
return(words)
}
hello("Lisa")
[1] "Hello Lisa"
hello("Ben")
[1] "Hello Ben"
function
(arg1, arg2, ...)
{...}
return
statementmySum <- function(a, b){
sum <- a + b
return(sum)
}
mySum(a = 4, b = 10)
[1] 14
mySum(a = 4, b = NA)
[1] NA
addTwo <- function(x) {
x <- x + 2
return(x)
}
x <- 6
addTwo(x)
[1] 8
x # x is still as before
[1] 6
x <- addTwo(x) # the result of the function is assigned to the variable x
x # now x has changed
[1] 8
Variables which are declared inside a function are not accessible from outside the function
f <- function(x, y) {
z <- x + y
return(x)
}
f(2, 3)
[1] 2
z
Error in eval(expr, envir, enclos): object 'z' not found
Variables which were defined outside of a function are also visible inside the function
y <- 5
h <- function(x) {
return(x*y)
}
h(2)
[1] 10
But what happens, if the object y
is removed from the global environment?
rm(y)
h(2)
Error in h(2): object 'y' not found
Never use global variables inside a function!
sapply
functiondata.frame
lapply
, sapply
, vapply
, …countNA(titanic$pclass)
[1] 0
countNA(titanic$sex)
[1] 0
countNA(titanic$age)
[1] 263
countNA(titanic$name)
[1] 0
sapply
waysapply(titanic, countNA)
X.1 X pclass survived name sex age embarked
0 0 0 0 0 0 263 0