1). For loop
x <- seq(1, 100, by=1);
xsquared = NULL
for (n in 1:100)
{
xsquared[n] = x[n]^2
}
2). Repeat statement
sum <- 1;
repeat
{
sum <- sum + 2;
print(sum);
if (sum > 11)
break;
}
3). While loop
x<-0;
while (x < 10)
{
x <- x + 4;
print (x);
if ( x = 8)
{
next;
}
}
4). apply(x, MARGIN, FUN, ARGs) fpr 2-dimensional data
x <- cbind(x1 = 3, x2 = c(4:1, 2:5));
dimnames(x)[[1]] <- letters[1:8];
apply(x, 2, mean);
col.sums <- apply(x, 2, sum);
row.sums <- apply(x, 1, sum);
5). tapply(vector, factor, FUN) ##Apply a function over a ragged array
x<-c(1,2,3,4,5,6,7,8);
names(x)<-c("a","a","b","a","b","a","b","a");
tapply(x,factor(names(x)),mean);
6). lapply() and apply()
x <- list(a = 1:10, b = (-3:3)^2, lv = c(TRUE,FALSE,FALSE,TRUE));
# compute the list mean for each list element
lapply(x, mean);
sapply(x,mean);