# Some notes on R -- jfm, august 2009, 2010 # starts a comment that continues for the remainder of the record Big picture language features -- more later: interpretive object-oriented coercion # both of these can be recycling # very dangerous! lexical scoping natural and unnatural looping gui vs batch and directory reference source("infile.name") sink("outfile.name") and sink() to discontinue .RData and .Rhistory help(command) q() to stop Details constants: the usual: 2, -3, 7.5e-3, "TRUE", "the quick brown fox" the unusual: pi scalar (vector!) variables x, X (case sensitive), this, that.one assignment > x <- 5 arithmetic +, -, /, * comparison <, <=, >, >=, ==, != (logical &, |, !(not)) > .3 == (.1 + 2/5) # be very careful with this!!!! functions the usual: sin, cos, exp, log, etc. the useful: seq, rep, ... # %/% int divide, x %% y (x mod y) the unusual: choose, ... > choose(7,2) vectors > v <- c(-2, -1, 0, 1, 2) # *** important function c() *** > w <- (-2:2) # sequence (or use seq(-2,2) ) > v + w > v * w # elementwise multiplication > v %*% w # vector multiplication > outer(v,w) # outer product v w' (or v%o%w) > crossprod(w,v) # inner product > t(w) %*% v # inner product indexing and subsets > v[2:4] > v > 1 > w[ v > 1 ] # example of coercion > is.vector(w) # is this thing a vector? > (1:10)[c(5,3,1)] > length((1:10)[c(5,3,1)]) > sum((1:10)[c(5,3,1)]) # also cumsum, diff > prod((1:10)[c(5,3,1)]) # also cumprod, cummax, cummin matrices > A <- matrix( c(2,1,0,0,0,1,2,1,0,0, + 0,1,2,1,0,0,0,1,2,1,0,0,0,1,2), 5, 5) # + was automatic # byrow = FALSE is default > is.matrix(A) # is this thing a matrix? > nrow(A) > ncol(A) > row(A) > col(A) > t(A) # transpose ************** > cbind(A,w) # attach matrix by columns > rbind(A,v) # attach matrix by row > diag(A) # vector from diagonal elements > diag( c(1:5) ) # diagonal matrix from vector subsets > A[,4] # column 4 > A[3:5,] # last 3 rows > A[2,4] # single element operations > A*w # oops! > A %*% w # that's better > t(w) %*% A %*% w # quadratic form > solve(A,w) # solve linear system Ax=w > chol(A) # Cholesky factor A = R'R, R upper tri > forwardsolve(L,w) # solve Lx=w where L is lower triangular > backsolve(U,w) # solve Ux=w where U is upper triangular > sqrt(det(A)) # one way to get det(A)**(1/2) > R <- chol(A) # Cholesky factorization > prod(diag(R)) # better way if A is pos def looping a stupid example > for (i in 1:5) { for (j in 1:5) { I[i,j] <- round(1/(abs(i-j)+1)) }} and conditional execution > for (i in 1:5) { if ( i < 5) v[i] <- 2 else v[i] <- 3 } > # in both cases, if referencing elements, the vector/matrix must > # be previously defined