# Factorial Implementations fac <- function(n) { ans <- 1 for(i in seq(n)) ans <- ans * i ans } fac <- function(n) if (n <= 0) 1 else n * fac(n - 1) fac <- function(n) prod(seq(n)) fac <- function(n) gamma(n+1) # These are slightly modified versions of Peter Dalgaard's # subset and transform functions for data frames. subset <- function (x, subset, select, ...) { if (missing(subset)) r <- TRUE else { e <- substitute(subset) r <- eval(e, x, sys.frame(sys.parent())) r <- r & !is.na(r) } if (missing(select)) vars <- TRUE else { nl <- as.list(1:ncol(x)) names(nl) <- names(x) vars <- eval(substitute(select), nl, sys.frame(sys.parent())) } x[r, vars, drop = FALSE] } transform <- function (x, ...) { e <- eval(substitute(list(...)), x, sys.frame(sys.parent())) tags <- names(e) inx <- match(tags, names(x)) matched <- !is.na(inx) if (any(matched)) { x[inx[matched]] <- e[matched] x <- data.frame(x) } if (!all(matched)) data.frame(x, e[!matched]) else x } # Examples, using the air data frame. # 1) Select all cases where ozone > 3 high1 <- subset(air, ozone > 3) # 2) Select all cases where ozone > 3 # Variables from ozone to temperature only high2 <- subset(air, ozone > 3, select = ozone:temperature)) # 3) Transform, creating one new variable and replace one old one names(air) new.air <- transform(air, new = -ozone, temperature = (temperature-32)/1.8) names(new.air)