V2 Flashcards
More Introduction to R
name two options of control structures
- branching : if, else if, switch
- looping: while, for, repeat
how to code if-statement
if(class(box) == "character"){ right(box) }else{ left(box) }
example:
if(all(x<5)) print - check if all numbers are smaller than 5 in vector
if(any(x<5)) print - check if at leat 1 is smaller than 5
how to code switch-statement
switch(class(box)), logical = left(x), numeric = middle(x), character= right (x) )
how to code else if-statement
code same as if statement as second or third line
how to code for-statement
for(x in 1:10){ box = box -x} - take x elements out of the box
how to code while-statement
box
Comparisons operators (6)
== - equal to != - not equal to < - smaller than > - lager than >= - smaller or equal to >= - larger or equal to
how to use &
& is vectorized, can be used for logical vectors
&& not vectorized, takes the first element from a vector
what happens at combination of if and & , |
- if needs single logical value
- so output from & and | cannot be used directly
how to use pairwise statements
A&B - pairwise AND
A|B pairwise OR
- > can store in a subset
- > can also be used for matrices
use lapply (code)
lapply(X, FUN,…) - repeat a function to each element in a vector or list
na.rm to use if there is NA
use apply (code)
apply(X,Margin, FUN, …) repeat function to each row or column in a matrix
margin = 1 , rows
margin = 2 , columns
margin = c(1,2), rows and columns
what happens with lapply / apply results
- normally give back list
- use unlist function to get vector
how to code a function
define a function with the keyword function
example:
boxwood
function parameter theory: pass-by-value
function parameters get copied into the function, changing them does not alter the state of the variable that was passed