## Learn R in 15 minutes ## http://homepages.math.uic.edu/~jyang06/stat411/stat411.html ## http://www.math.uic.edu/~jyang06/stat411/handouts/handout3.pdf ## R # http://cran.r-project.org/ ## Why R? ## R <-> SAS ## [1] Download R and install R via http://cran.r-project.org/ ## [2] Use R as calculator ## [3] Use R to plot graph f <- function(x) { x*sin(x); } plot(f, -20*pi, 20*pi) abline(0,1,lty=2) # add a dash line with intercept 0 and slope 1 abline(0,-1,lty=2) # add a dash line with intercept 0 and slope -1 ## [4] Use R for data analysis library(MASS) # load package "MASS" for data set "hills" summary(hills) # list summary statistics of variables in "hills" cor(hills) # correlation matrix for "hills" pairs(hills) ## [5] Use R for simulations n <- 100000 # number of random experiments x <- c(0,1) # sample space for tossing a coin, 0--Tail, 1--Head simu <- sample(x, size=n, replace=TRUE) sum(simu) # count number of heads x <- c(1,2,3,4,5,6) # sample space for casting a die simu <- sample(x, size=n, replace=TRUE) sum(simu==3) # count number of "3" ## [6] logical operation 1==3 1==1 ## [7] run a loop factorial(5) answer = 1 for(i in 1:5) { answer = answer*i; } answer f.self <- function(n) { answer=1; for(i in 1:n) { answer = answer*i; } answer } f.self(5) ##### R tips ### R tips No. 1: how to use R helps? # want to know how to use function "runif" ?runif # want to know how to generate random numbers from normal distribution help.search("normal distribution") ?Normal ### R tips No. 2: how to print or save R graphs? # if use menu operations: [1] click the R graph window; # [2] (menu)File --> print or File --> Save as # if use R command lines: for example, to save the graph into a file "normal.ps" x <- rnorm(1000, mean=1, sd=2) postscript("normal.ps",paper="special",width=8,height=7,horizontal=F) par(mfrow=c(1,1)) hist(x, freq=F) curve(dnorm(x, mean=1, sd=2), lwd=2, lty=2, add=T) dev.off() ## R tips No. 3: how to count the computation time (in seconds) tempt <- proc.time() temp <- runif(10000000) proc.time()-tempt ## R tips No. 4: generating random numbers from distributions of standard parameter families ## available R functions # rbeta -- The Beta Distribution # rbinom -- The Binomial Distribution # rcauchy -- The Cauchy Distribution # rchisq -- The (non-central) Chi-Squared Distribution # rexp -- The Exponential Distribution # rf -- The F Distribution # rgamma -- The Gamma Distribution # rgeom -- The Geometric Distribution # rhyper -- The Hypergeometric Distribution # rlnorm -- The Log Normal Distribution # rlogis -- The Logistic Distribution # rmultinom -- The Multinomial Distribution # rnbinom -- The Negative Binomial Distribution # rnorm -- The Normal Distribution # rpois -- The Poisson Distribution # rsignrank -- Distribution of the Wilcoxon Signed Rank Statistic # rt -- The Student t Distribution # runif -- The Uniform Distribution # rweibull -- The Weibull Distribution # rwilcox -- Distribution of the Wilcoxon Rank Sum Statistic