Docsity

S-Plus and R: A Comparison of Statistical Computing Tools - Prof. A. John Bailer, Study Guides, Projects, Research of Statistics

Toggle sidebar
bg1
Week 12+ [12, 14 Nov.] Class Activities
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
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f

Partial preview of the text

Download S-Plus and R: A Comparison of Statistical Computing Tools - Prof. A. John Bailer and more Study Guides, Projects, Research Statistics in PDF only on Docsity!

Week 12+ [12, 14 Nov.] Class Activities

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

1 BASIC CONCEPTS

*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

2 USING SAS PROCEDURES

  • Introduce the idea of SAS system options

  • Briefly review statements that can be used with most

procedures (BY, WHERE, TITLE, FOOTNOTE, LABEL,

FORMAT)

  • 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

  • PROC FREQ for one-way frequency tables and n-way cross-

tabulations

  • PROC UNIVARIATE for descriptive statistics and

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()

  • table() –

frequency tables

  • summary()

  • means(), var(),

quantile(), etc.

  • sort(), index()

  • ?command

3 REPORT WRITING

  • Introduce the Output Delivery System (ODS) for customizing

procedure output

  • PROC TABULATE for producing nicely-formatted tables

No ODS analog

although can save

graphics in a host of

different formats

4 AN INTRODUCTION TO STATISTICAL MODELING

  • PROC REG for linear modeling (a very basic introduction)

  • PROC GLM for anova models

lm (linear models),

glm (generalized

linear models)

5 HIGH-RESOLUTION GRAPHICS AND FORMATS

  • Introduce concepts related to high-resolution graphs

  • PROC GCHART and PROC GPLOT for producing high-

resolution graphs

  • SAS-supplied formats and PROC FORMAT for user-defined

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

Overview and abbreviated history

(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

  1. menu
  2. > help() [where “>” is the default command prompt in S/R]
  3. > ?quantile

> 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

[1] 3.

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

comments begin with a pound sign

x <- sqrt(3) # arrow is the preferred assignment operator

y _ 7 # underscore can also be used but makes it

harder to read code

x

[1] 1.

y

[1] 7

  • “x <- sqrt(3)” is often read “x gets the square root of 3”

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

  • one dimensional object containing elements of the same mode

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)

[1] 10

> 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

  • rectangular object containing elements of the same mode

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

[,1] [,2] [,3]

[1,] 1 4 7

[2,] 2 5 8

[3,] 3 6 9

xmat

[,1] [,2] [,3]

[1,] 11 12 13

[2,] 14 15 16

[3,] 17 18 19

xmat

[,1] [,2] [,3] [,4]

[1,] 1 5 9 13

[2,] 2 6 10 14

[3,] 3 7 11 15

[4,] 4 8 12 16

xmat

[,1] [,2] [,3] [,4]

[1,] 1 2 3 4

[2,] 5 6 7 8

[3,] 9 10 11 12

[4,] 13 14 15 16

*** attributes**

dimnames(xmat1) <- list(c(“R1”,”R2”,”R3”),paste(“C”,1:3,sep=””))

> xmat

C1 C2 C

R1 1 4 7

R2 2 5 8

R3 3 6 9

length(xmat1)

[1] 9

mode(xmat1)

[1] "numeric"

dim(xmat1) # attrib beyond vectors

expect data to be in data frames

*** constructing**

  1. from objects

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

1 0.34780031 T

2 3.14930814 T

3 0.06120061 T

4 3.67502557 T

5 0.76163078 T

6 3.32734193 T

7 2.25088304 T

8 7.04511215 T

9 4.89744245 T

10 1.77831910 T

data.class(my.df)

[1] "data.frame"

length(my.df)

[1] 2

mode(my.df)

[1] "list"

class(my.df)

[1] "data.frame"

attributes(my.df)

$names:

[1] "y" "trt"

$row.names:

[1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10"

$class:

[1] "data.frame"

data.class(my.df)

[1] "data.frame"

  1. coercing matrices

xmat1.df <- as.data.frame(xmat1)

xmat

xmat1.df

  1. read.table (more to come)

*** attributes**

mode: “list”

length: 2

names: columns

row.names

col.names

dim

dimnames

*** subscripting**

my.df[1,]

y trt

1 0.3478003 T

my.df[,2]

[1] T1 T1 T1 T1 T1 T2 T2 T2 T2 T

my.df$trt

[1] T1 T1 T1 T1 T1 T2 T2 T2 T2 T

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]

[1] 5

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

[1] A B C C B B A A C

attributes(intensity)

$levels:

[1] "A" "B" "C"

$class:

[1] "factor"

codes(intensity) # transform to numeric vector

[1] 1 2 3 3 2 2 1 1 3

ord.int <- ordered(c(“A”,”B”,”B”,”C”,”A”,”C”),

levels=c(“A”,”B”,”C”))

ord.int

[1] A B B C A C

A < B < C

attributes(ord.int)

$levels:

[1] "A" "B" "C"

$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))