























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!
























C:\Documents and Settings\John Bailer\My Documents\baileraj\
Classes\Fall 2003\sta402\handouts\week12-11nov03.doc
TOPICS IN STATISTICAL PROGRAMMING (varies)
Introduction to quantitative programming in S-Plus/R
objects – vectors, lists, matrices, dataframes
reading data [ scan , read.table, sas.get ]
summarizing data sets [ mean, var, summary, table ]
graphical displays [ plot, pairs , trellis displays]
writing functions
References:
Venables WW and Ripley BD. 1997. Modern Applied Statistics with S-
Plus. Springer-Verlag.
Venables WW and Ripley BD. 2000. S Programming. Springer-Verlag.
Spector P. 1994. An introduction to S and S-Plus. Duxbury Press
Krause A and Olson M. 1997. The Basics and S and S-Plus.
Springer.
S-Plus for Windows Documentation
http://216.211.131.2/support/doc_splus_win.asp
Getting Started with S-Plus for Windows (GUI stuff)
http://216.211.131.2/support/splus60win/tutorial.pdf
R Project downloads, FAQs and manuals http://www.r-project.org/
Past SAS activities and how these might relate to S-Plus/R ideas
week SAS ideas S-Plus/R ideas
*Review basic concepts of statistical computing and research
data management
Introduce SAS data sets
Review the form of SAS Statements and SAS names
Introduce SAS procedures
Review the structure of SAS programs
Describe SAS data libraries and what they can contain
Show documenting SAS programs using comments
Illustrate running SAS programs and basic debugging
Introduce language
elements
Objects in S-Plus/R
(scalars, vectors,
matrices,
dataframes, lists)
Object-oriented
functionality
Introduce the idea of SAS system options
Briefly review statements that can be used with most
procedures (BY, WHERE, TITLE, FOOTNOTE, LABEL,
PROC CONTENTS for describing a data set
PROC PRINT for listing the observations in a data set
PROC CHART and PROC PLOT for producing low resolution
graphs
tabulations
distributional information
PROC MEANS for descriptive statistics
PROC SORT for sorting a data set
SAS documentation and the online help system
options()
titles build into
most displays
names(dataframe)
low resolution
graphs via printer()
frequency tables
summary()
means(), var(),
quantile(), etc.
sort(), index()
?command
procedure output
No ODS analog
although can save
graphics in a host of
different formats
PROC REG for linear modeling (a very basic introduction)
PROC GLM for anova models
lm (linear models),
glm (generalized
linear models)
Introduce concepts related to high-resolution graphs
PROC GCHART and PROC GPLOT for producing high-
resolution graphs
formats
plot, pairs, boxplot,
11 SAS/IML Programming
Basic matrix concepts: rows, columns, scalars
matrix operators
subscripting
matrix functions
creating matrices from data sets and vice versa
sample applications
matrix manip. part
of the language
(from Krause/Olson and R project page)
S is a quantitative programming environment developed at AT&T Bell Labs
1976 start
1981 rewrite in C and port to unix
1985 function concept introduced
1987 S-Plus, a supported and extended version of S, started
1989 S-Plus for DOS
1993 S-Plus for Windows
1997 GUI for S-Plus for Windows
ca 1997 R development team working (after R started by Robert Gentleman and
Ross Ihaka of the Statistics Department of the University of Auckland
R is a language and environment for statistical computing and graphics.
GNU project which is similar to the S language, different implementation of S
provides a wide variety of statistical (linear and nonlinear modelling, classical statistical tests,
time-series analysis, classification, clustering, ...) and graphical techniques, and is highly
extensible.
S language is often the vehicle of choice for research in statistical methodology, and R provides
an Open Source route to participation in that activity.
One of R's strengths is the ease with which well-designed publication-quality plots can be
produced, including mathematical symbols and formulae where needed. Great care has been
taken over the defaults for the minor design choices in graphics, but the user retains full control.
R is available as Free Software under the terms of the Free Software Foundation's GNU General
Public License in source code form. It compiles and runs out of the box on a wide variety of
UNIX platforms and similar systems (including FreeBSD and Linux). It also compiles and runs
on Windows 9x/NT/2000 and MacOS.
GUI vs. Command Line
S-Plus has a Graphical User Interface available (GUI) -- see
http://216.211.131.2/support/splus60win/tutorial.pdf
for more information
We focus on command line interactions with S-Plus/R
Getting help
> help(quantile) # for help on specific command
> help(“^”) # for help on operator
Quick motivating example I - “one liner” to estimate PI using MC simulation
# Estimating PI using MC simulation
pi.est <- 4*( sum(runif(4000) <= sqrt(1-runif(4000)^2))/4000 )
pi.est
Quick motivating example II – function to estimate PI using MC simulation
# Estimating PI using MC simulation
pi.est.fcn <- function(nsims=1400) {
xsim <- runif(nsims)
ysim <- runif(nsims)
icheck <- ( ysim <= sqrt(1-xsim^2) )
points.under <- sum(icheck)/nsims
piest <- 4*points.under
se.piest <- 4sqrt(points.under(1-points.under)/nsims)
CL <- piest + c(-1,1)qnorm(.975)se.piest
list(est.pi = piest, se.est.pi = se.piest, conf.int = CL)
xsim
ysim
Syntax
Assignments
x <- sqrt(3) # arrow is the preferred assignment operator
y _ 7 # underscore can also be used but makes it
x
y
Continuation
> x <- sqrt(
“>” is the command prompt while “+” is a continuation prompt
the history of previous commands can be navigated/edited by using arrow keys
Object names
any combination of letters, numbers and periods (can’t begin with a number)
SAS user warning – NO UNDERSCORES ALLOWED!
CaSe-SeNiSiTiVe!
> Temp <- 172
> temp
Problem: Object "temp" not found
Use traceback() to see the call stack
Deleting objects
rm(Temp) # delete/remove object
undo(“Temp”) # recovers accidently deleted object
List all objects (can look in the GUI Object Explorer or.. .)
objects() # names of objects you created
[1] ".Last.value" "Temp" "last.dump" "x" "y"
search() # directories searched for objects
[1] "D:\baileraj\Classes\Fall 2003\sta402\R-S-programs"
[2] "splus"
[3] "stat"
[4] "data"
[5] "trellis"
[6] "nlme3"
[7] "menu"
[8] "sgui"
[9] "main"
Vectors
x1 <- 1:
x2 <- seq(1,5,by=0.25)
x3 <- c(1:3, 4:7, 8, 9 , 10) # c() combines elements/vectors
x4 <- rep(1,10)
x5 <- rep(1:4, rep(3,4))
vector attributes: length, mode
can add names:
names(x1) <- letters[1:length(x1)]
> length(x1)
> mode(x1)
[1] "numeric"
> class(x1)
[1] "named"
> attributes(x1)
$names:
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
*** subscripting vectors**
> x1[] # all elements – x
a b c d e f g h i j
> x1[c(1,10)] # 1st and 10th elements
a j
> x1[-c(1,10)] # all but 1st and 10th elements
b c d e f g h i
> x1[x1>5] # only elements > 5
f g h i j
> x1[c("a","b")]
a b
Matrices
xmat1 <- cbind(1:3, 4:6, 7:9)
xmat2 <- rbind(11:13, 14:16, 17:19)
xmat3 <- matrix(1:16,nrow=4) # default: fill by column
xmat4 <- matrix(1:16,nrow=4,byrow=T)
xmat
xmat
xmat
xmat
*** attributes**
dimnames(xmat1) <- list(c(“R1”,”R2”,”R3”),paste(“C”,1:3,sep=””))
> xmat
length(xmat1)
mode(xmat1)
[1] "numeric"
dim(xmat1) # attrib beyond vectors
expect data to be in data frames
*** constructing**
y1 <- 2 + 1.5*rnorm(5)
y2 <- 4 + 1.5*rnorm(5)
y <- c(y1,y2)
trt <- rep(c(“T1”,”T2”),c(5,5))
my.df <- data.frame(y,trt)
my.df
y trt
data.class(my.df)
[1] "data.frame"
length(my.df)
mode(my.df)
[1] "list"
class(my.df)
[1] "data.frame"
attributes(my.df)
$names:
[1] "y" "trt"
$row.names:
$class:
[1] "data.frame"
data.class(my.df)
[1] "data.frame"
xmat1.df <- as.data.frame(xmat1)
xmat
xmat1.df
*** attributes**
mode: “list”
length: 2
names: columns
row.names
col.names
dim
dimnames
*** subscripting**
my.df[1,]
y trt
my.df[,2]
my.df$trt
search()
[1] "D:\baileraj\Classes\Fall 2003\sta402\R-S-programs"
[2] "splus"
[3] "stat"
[4] "data"
[5] "trellis"
[6] "nlme3"
[7] "menu"
[8] "sgui"
[9] "main"
length: number of components of list
mode: list
names: component names
*** subscripting**
$ operator with component name – e.g. my.lst$x1vec
number/name in [[]]
my.lst$x1vec
a b c d e f g h i j
my.lst[[1]]
a b c d e f g h i j
my.lst[[1]][5] # 5
th
element of first list component
e
my.lst[[2]][2,2]
Factors/Ordered Factors
categorical data
character vector with only certain strings allowed
stored as vector of integers
names stored as “levels” attribute
ordered factors include information on ordering of levels
e.g.
intensity <- factor(c(1,2,3,3,2,2,1,1,3),
levels = c(1,2,3),
labels = c(“A”,”B”,”C”))
intensity
attributes(intensity)
$levels:
$class:
[1] "factor"
codes(intensity) # transform to numeric vector
ord.int <- ordered(c(“A”,”B”,”B”,”C”,”A”,”C”),
levels=c(“A”,”B”,”C”))
ord.int
attributes(ord.int)
$levels:
$class:
[1] "ordered" "factor"
Graphics: command line
High level – yields complete plot (e.g. plot, boxplot, hist)
Low level – adds to existing plot (e.g. identify, abline)
Graphical parameters – set by “par”
Univariate data
barplot
boxplot
hist
dotchart
pie
qqnorm
Bivariate data
plot
barplot
boxplot
qqplot
Three dimensional
contour
persp
image
ylab=”Residuals”,xlab=”Predicted Total”)
points(jitter(fitted(nitro.linreg)),resid(nitro.linreg))
abline(h=0)
hist(resid(nitro.linreg),prob=T)
qqnorm(resid(nitro.linreg),ylab=”Residuals”)
Nitrofen data
Note: jitter in x-direction
conc
total
0 50 100 150 200 250 300
0
10
20
30
Predicted Total
Residuals
10 15 20 25 30 35
0
5
10
-15 -10 -5 0 5 10 15
resid(nitro.linreg) Quantiles of Standard Normal
Residuals
-2 -1 0 1 2
0
5
10
par(par.old) # restore to previous setting
par(mfrow=c(3,2))
plot(nitro.linreg) # plot.lm behavior
Fitted : conc
Residuals
10 15 20 25 30 35
0
5
10
44
35
9
fits
sqrt(abs(Residuals))
10 15 20 25 30 35
1
2
3 44 35
9
Fitted : conc
total
10 15 20 25 30 35
0
10
20
30
Quantiles of Standard Normal
Residuals
-2 -1 0 1 2
0
5
10
44
35
9
Fitted Values
0.0 0.2 0.4 0.6 0.8 1.
0
5
10
Residuals
0.0 0.2 0.4 0.6 0.8 1.
0
5
10
f-value
total
Cook's Distance
0 10 20 30 40 50
0.10 1
44
9
plot(total~as.factor(conc))