###________ Section 1: Arithmetic and Assignment ________### 3*(2 + 1) g <- 4931 g g*1000 h <- c(15.1,11.3,10.0) h*2.7 ls() rm(g,h) #remove objects g & h ls() 2^c(1,2,3,4) #powers of two 0:10 #sequence from 0 to 10 3:-7 #sequence from 3 down to -7 seq(-3,3,by=0.5) #sequence by specified increment #scripts & functions for STAT 221 source("http://www.uvm.edu/~rsingle/stat221/data/scripts-221.R") murder illit states mean(murder) median(murder) murder > 12 #logical operator murder / illit #murders per 1000 illiterate abs(murder - mean(murder)) #abs difference from the mean ###________ Section 2: Extracting Data; Subscripts ________### murder[1:3] #1st 3 elements of murder murder[murder > 12] #elements of murder where murder>12 is TRUE states[murder > 12] #elements of states where murder>12 is TRUE illit[states == "CA"] #illiteracy rate for CA murder murder[-1] #murder without 1st element murder[-7] ###________ Section 3: Plotting ________### data(state) ls() state.x77 murder <- state.x77[,5] illit <- state.x77[,3] states <- state.abb plot(illit,murder) abline(2.4, 4.3) identify(illit, murder, states, col = 2) #interactive function #NOTE: click "finish" in the upper right of the plot window when done plot(illit,murder, type="n") #type="n" means nothing plotted text(illit,murder,states,col=2) #----- summary(murder) vhigh <- murder >= 10.68 high <- murder >= 6.85 & murder < 10.68 low <- murder >= 4.35 & murder < 6.85 vlow <- murder < 4.35 plot(illit,murder,type = "n") points( illit[vhigh],murder[vhigh],pch="H", col=1 ) points( illit[high], murder[high], pch="h", col=2 ) text( illit[low], murder[low], "l", col=3 ) text( illit[vlow], murder[vlow], "L", col=4 ) #----- A fancy plot state.x <- state.center$x state.y <- state.center$y plot(state.x,state.y,type="n") text( state.x[vhigh],state.y[vhigh],state.abb[vhigh],col=1) text( state.x[high], state.y[high], state.abb[high], col=2) text( state.x[low], state.y[low], state.abb[low], col=3) text( state.x[vlow], state.y[vlow], state.abb[vlow], col=4) legend(-77,31, c("VHIGH","HIGH","LOW","VLOW"),pch="*",col=1:4,cex=.5) title(main = "Quartiles of murder rates by state", col = 6) ###________ Section 4: CLT demo & loops ________### x <- rchisq(2000,3) hist(x) xbar <- vector(length=500) for(i in 1:500) { tmp <- sample(x,64,replace=T) xbar[i] <- mean(tmp) } xbar hist(xbar) mean(x) mean(xbar) sd(x) sd(xbar) sd(x)/sqrt(64) ###________ Section 5: Writing Functions ________### stdev <- function(x){ return(sqrt(var(x)))} stdev(murder) ###________ Section 6: Matrices ________### y <- matrix(data=1, nr=3, nc=2) y y[,1] # column 1 of y y[2,] # row 2 of y t(y) # transpose of y t(y) %*% y # matrix multiplication y %*% t(y) y %*% y z <- matrix(nr=3, nc=2) z