## illustrating the need for curly brackets (or not with for loops, ## functions, etc). You don't need them if your function/loop/etc is ## only one line n <- -5 for(i in 1:n) print(i^2) ## creating a matrix matrix(1:18, nrow=4) ## creating a function with two arguments my.sum <- function(a, b) { c <- a/b return(c) } ## and applying that function to a range of values for one variable, ## but holding the other constant sapply(1:10, my.sum, b=5) sapply(1:10, my.sum, a=5) ## writing a figure straight to a pdf pdf('~/Desktop/myplot.pdf', height=4, width=4) par(oma=c(0.1,0.1,0.1,0.1), mar=c(3, 3, 0.1, 0.1), mgp=c(1,0.4,0)) plot(1:10, col='blue', pch=16, las=1) dev.off() ## creating another matrix m <- matrix(1:20, nrow=4) ## applying the "sum" function over rows vs columns (and, of course, ## you could also apply your own function) apply(m, MARGIN=1, FUN=sum) apply(m, MARGIN=2, FUN=sum) ## doing the same thing much less elegantly with an sapply sapply(1:nrow(m), FUN=function(i) sum(m[i,])) sapply(1:ncol(m), FUN=function(i) sum(m[,i])) ## creating a data-frame dd <- data.frame(bird.mass=runif(20), bird.age=sample(1:4, size=20, replace=TRUE), bird.iq=sample(1:3, size=20, replace=TRUE)) ## and then applying a function to that data-frame, using apply: ## ## e.g., if our equation was: ## bird.score = bird.mass + bird.age^bird.iq eq7 <- function(a, b, c) a + b^c dd$bird.score <- mapply(eq7, a=dd$bird.mass, b=dd$bird.age, c=dd$bird.iq) ## could also do this just directly, but this is not always possible dd$bird.mass + dd$bird.age^dd$bird.iq