2.1 Basic loops in R (3)

This time instead of using the : expression for looping lets use the function seq()

Example

nall <- 5
for (n in seq(2,10,2)) {
nall <- nall * n
print(nall)
}

## [1] 10
## [1] 40
## [1] 240
## [1] 1920
## [1] 19200

Rememember! Every variable you use in a loop has to have an initial value. Thus we set nall <- 5 at the start of our script. Try to comment the first line using the symbol # and rerun everything from the top. Read the error!

2.2 Filters (1)

Filtering data in R can be done in one line. In most cases filters are applied for the whole length of an object (for example for the whole length a vector). Although sometimes that's not the case and an if and for combinations is necessary. The typical statements for filtering and conditions are the following:

== Checks if A and B are equal.

!= Checks if A and B are NOT equal.

> Checks if A is greater than B.

< Checks if A is lower than B.

>= Checks if A is greater than OR equal to B.

<= Checks if A is lower than OR equal to B.

Multiple conditions can be tested in one if using the statements & and |.

2.4 Loops + Conditions (2)

Example

loop_number <- 10
loop_check <- TRUE
if (loop_check) {
for (n in 1:loop_number) {
print(paste("We are on the loop ",n," of 10.",sep=""))
if (n==10) {loop_number <- 12} # This will NOT affect the loop_number in for()
} # since the loop started with a different initial
} # value!

## [1] "We are on the loop 1 of 10."
## [1] "We are on the loop 2 of 10."
## [1] "We are on the loop 3 of 10."
## [1] "We are on the loop 4 of 10."
## [1] "We are on the loop 5 of 10."
## [1] "We are on the loop 6 of 10."
## [1] "We are on the loop 7 of 10."
## [1] "We are on the loop 8 of 10."
## [1] "We are on the loop 9 of 10."
## [1] "We are on the loop 10 of 10."

3. Handling the Non-Avaliable (NA) Values.

3.1 Non-Avaliable in functions (1)

Use the na.rm=T argument in functions.

Example

v <- c(1:5,NA,7) # Creating a vector that includes a NA.
v

## [1] 1 2 3 4 5 NA 7

mean(v) # Mmm R doesn't like (or overlikes) NAs.

## [1] NA

mean(v,na.rm=T) # Thus we have to force R to ignore them!

## [1] 3.666667

3.2 Non-Avaliable in datasets

Use the is.na() and !is.na() functions.

Example

v <- c(1:5,NA,7) # Creating a vector that includes a NA.
v[!is.na(v)] # Get all values that are NOT (!) NA using a filter.