# example of creating a function sumdice <- function(n) { k <- sample(1:6,size=n,replace=TRUE) return(sum(k))} n <- 2 repitions <- 100 outcomes <- rep(0,repitions) # example of a for loop for (i in 1:repitions){ outcomes[i] <- sumdice(n) } hist(outcomes) # Data frame is a list of variables of the same length, but not necessarily the same type library(DAAG) data(ais) help(ais) is.data.frame(ais) plot(ais) head(ais) names(ais) attach(ais) library(lattice) xyplot(bmi~ssf|sport,groups=sex,pch=16,col=c(2,3),data=ais,xlab="Skin-fold",ylab="Body mass") legend(x="topleft",legend=c("Females","Males"),pch=16,col=c(2,3)) x <- ais[,"bmi"] y <- ais[,"pcBfat"] plot(x,y,type="n",xlab="Body mass index",ylab="Percent body fat") sport.name <- levels(sport) n <- length(sport.name) for (j in 1:n) { I <- sport==sport.name[j] x <- ais[I,"bmi"] y <- ais[I,"pcBfat"] star <- matrix(unlist(ais[I,1:5]),ncol=5) symbols(x,y,stars=star,add=TRUE,fg=j) } legend(x="topleft",legend=sport.name,pch=16,col=1:n) x <- ais[,"bmi"] y <- ais[,"pcBfat"] plot(x,y,type="n",xlab="Body mass index",ylab="Percent body fat") genders <- levels(sex) n <- length(genders) for (j in 1:n) { I <- sex==genders[j] x <- ais[I,"bmi"] y <- ais[I,"pcBfat"] star <- matrix(unlist(ais[I,1:5]),ncol=5) symbols(x,y,stars=star,add=TRUE,fg=j) } legend(x="topleft",legend=genders,pch=16,col=1:n)