for
loop
for
loops iterate over elements of a looping vector.
Syntax
for(variable in sequence) {
statements
}
Example
mydf <- iris
myve <- NULL
for(i in seq(along=mydf[,1])) {
myve <- c(myve, mean(as.numeric(mydf[i,1:3])))
}
myve[1:8]
## [1] 3.333333 3.100000 3.066667 3.066667 3.333333 3.666667 3.133333 3.300000
Note: Inject into objecs is much faster than append approach with c
, cbind
, etc.
Example
myve <- numeric(length(mydf[,1]))
for(i in seq(along=myve)) {
myve[i] <- mean(as.numeric(mydf[i,1:3]))
}
myve[1:8]
## [1] 3.333333 3.100000 3.066667 3.066667 3.333333 3.666667 3.133333 3.300000
Conditional Stop of Loops
The stop
function can be used to break out of a loop (or a function) when a condition becomes TRUE
. In addition, an error message will be printed.
Example
x <- 1:10
z <- NULL
for(i in seq(along=x)) {
if(x[i] < 5) {
z <- c(z, x[i]-1)
} else {
stop("values need to be < 5")
}
}
while
loop
Iterates as long as a condition is true.
Syntax
while(condition) {
statements
}
Example
z <- 0
while(z<5) {
z <- z + 2
print(z)
}
## [1] 2
## [1] 4
## [1] 6
The apply
Function Family
apply
Syntax
apply(X, MARGIN, FUN, ARGs)
Arguments
X
:array
,matrix
ordata.frame
MARGIN
:1
for rows,2
for columnsFUN
: one or more functionsARGs
: possible arguments for functions
Example
apply(iris[1:8,1:3], 1, mean)
## 1 2 3 4 5 6 7 8
## 3.333333 3.100000 3.066667 3.066667 3.333333 3.666667 3.133333 3.300000
tapply
Applies a function to vector components that are defined by a factor.
Syntax
tapply(vector, factor, FUN)
Example
iris[1:2,]
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
tapply(iris$Sepal.Length, iris$Species, mean)
## setosa versicolor virginica
## 5.006 5.936 6.588
sapply
and lapply
Both apply a function to vector or list objects. The lapply
function always returns a list object, while sapply
returns vector
or matrix
objects when it is possible.
Examples
x <- list(a = 1:10, beta = exp(-3:3), logic = c(TRUE,FALSE,FALSE,TRUE))
lapply(x, mean)
## $a
## [1] 5.5
##
## $beta
## [1] 4.535125
##
## $logic
## [1] 0.5
sapply(x, mean)
## a beta logic
## 5.500000 4.535125 0.500000
Often used in combination with a function definition:
lapply(names(x), function(x) mean(x))
sapply(names(x), function(x) mean(x))