SOME NOTES ON R FACILITIES FOR USE IN ASSIGNMENT 1 Debugging: options(warn=2) Have warnings treated as errors (so they're easier to debug) traceback() Right after an error, shows which function it occured in options(error=dump.frames) Allow use of the debugger after an error debugger() Start up the debugger, right after an error Reading data from files: scan("file") Good for reading a vector of numbers read.table("file",head=F) Reads data with one case per line, returning it as a "data frame" as.matrix(df) Converts a data frame to a matrix. Operations on matrices can be much faster than on data frames Sequences and grids: 1:n Vector c(1,2,...,n-1,n). Warning: using 1:0 doesn't give a zero-length vector! seq(a,b,length=n) sequence of n numbers equally-spaced, starting at a and ending at b rep(v,times=n) Vector v repeated n times rep(v,each=n) Vector formed by repeating each element of v n times Plotting: par(mfrow=c(1,2)) Put two plots on one page pdf("file.pdf",width=w,height=h) Directs a plot to a PDF file, which plot(...) can then be viewed or printed with dev.off() acroread plot(x,y) Scatterplot of data in vectors x and y (which must be the same length) contour(gx,gy,M) Contour plot of data in the matrix M, with the vectors gx and gy giving the coordinates of rows and columns in M. Matrices: as.vector(m) Useful for converting a 1-by-n or n-by-1 matrix to a plain vector %*% Does a matrix-by-matrix multiply, or a matrix-by-vector or vector-by-matrix multiply M[i,] The vector consisting of row i of M M[-i,] The matrix consisting of all rows of M EXCEPT row i (assuming i is positive). diag(v) Diagonal matrix with v on the diagonal; diag(n) with n scalar is an n-by-n identity matrix cbind(...), rbind(...) Put together matrices by concatenating vectors or matrices horizontally or vertically solve(M) Inverse of M; solve(M,v) solves M %*% x = v t(M) Transpose Programming: for (i in 1:n) Loop with i taking on values 1, 2, ..., n { ... Warning! Doesn't work if n is 0 } if (..c..) { ..A.. } If statement, does A if c is true, B otherwise, else { ..B.. } can omit the "else" part