您的当前位置:首页正文

r语言初学者指南

2022-11-18 来源:欧得旅游网
RforBeginners

ChineseEdition

0.1

EmmanuelParadis

´InstitutdesSciencesdel’Evolution

Universit´eMontpellierIIF-34095Montpellierc´edex05France

E-mail:paradis@isem.univ-montp2.fr

Co-translatedby:XFWang,YHXie,JTLiandGHDing

“Rforbeginners”

2002

R

2005

EmmanuelParadis

Chap1–2:

ALTEXChap3:

Chap4:

Chap5–7:

pwxf@hotmail.com

20063

c2002,2005,EmmanuelParadis󰀂

Permissionisgrantedtomakeanddistributecopies,eitherinpartorin

fullandinanylanguage,ofthisdocumentonanysupportprovidedtheabovecopyrightnoticeisincludedinallcopies.Permissionisgrantedtotranslatethisdocument,eitherinpartorinfull,inanylanguageprovidedtheabovecopyrightnoticeisincluded.

12

2.1..............................

2.2.....................

2.3..............................

3R

3.1.........

........................3.2.

........................3.3..............................3.4

......

........................3.4.1..........................3.4.2..

........................3.5

......

........................3.5.1..........................3.5.2..........................3.5.3.....

........................3.5.4.............3.5.5......................3.5.6..........

...............3.5.7.

...............3.5.8

...........

.

.

.............

4

R4.1

..........

.

...................4.1.1

.....................4.1.2

.........................4.2..........

....................4.3...........................4.4..............................4.5..........

....................4.6

gridlattice

...........................

13

357991114151518191924262730323234373737384142444549

5R

5.15.25.35.46R

6.16.2.

...............

............

........................................................................................

5656575962

R

65

............................65..............................67

6.37R

.........................68

71

1

R

.

R

R

R

RobertGentleman1SS

RossIhaka

R

AT&T

1

R

Insightful2

S-PLUS

RSIhaka&

RGentleman(1996)R-FAQ3

RGNUGeneralPublicLicence4

RRDevelopmentCoreTeamRUnixLinux(CFortran)Windows,LinuxMacintosh

ComprehensiveRArchiveLinuxNetwork(CRAN)5

LinuxCRAN

R

(jpg,png,bmp,ps,

)pdf,emf,pictex,xfig;

(P-)

R

R

S

6,

R

R

R

R

“object”

IhakaR.&GentlemanR.1996.R:alanguagefordataanalysisandgraphics.JournalofComputationalandGraphicalStatistics5:299–314.2

http://www.insightful.com/products/splus/default.asp3

http://cran.r-project.org/doc/FAQ/R-FAQ.html4

Formoreinformation:http://www.gnu.org/5

http://cran.r-project.org/6

Forexample:http://stat.cmu.edu/S/

1

1

20

R

20

R

2

2

R

R

‘>’

Windows

Rgui.exe

...)

(

R

R

.

(“assign”)

R

(object)

2.1

R

R

(C

Fortan,Pascal,...)

R

lm(y~x)

“x

y

R

(,ls())

R

R(

(object)

(objects)

)

functions(

)(p.26).

R

arguments−→options−→(argument)

function↑

defaultarguments

(

=⇒result

...)

R

3

R

R

(p.68)

R

,

(Fig.1)

(

)

keyboardcommands

-functionsandoperators󰀈

mouse

?

“data”objects

󰀄󰀄󰀄)󰀄screen

6?

“results”objects

󰀈

.../library/base/

/stast//graphics/

...

libraryoffunctions

-

󰀈XX

XXX

XzX

data

files

internet

PS

JPEG

...

ActivememoryHarddisk

Figure1:R

.

R

RHOME/library

base

(RHOME(packages)

R

(library)

R

,

)

R

R

(

base

RHOME/library/base/R/base)R

n

10

>n[1]10

1

n

4

print

,

print(n)(print)

(A–Za–z),

(0–9)

(.)

().

R

(Windows

x

X

)

2.2

R

(“assign”)

:

>n>n[1]>5>n[1]>x>X>x[1]>X[1]

<-1515->n5<-1<-10110

)

(R

>n>n[1]>n>n[1]

<-10+212

<-3+rnorm(1)2.208807

rnorm(1)(p.18)

0

1

:

5

>(10+2)*5[1]60

ls

:

>name<-\"Carmen\";n1<-10;n2<-100;m<-0.5>ls()[1]\"m\"\"n1\"\"n2\"\"name\"

R

pattern

(

pat)):

>ls(pat=\"m\")[1]\"m\"\"name\"

:

>ls(pat=\"^m\")[1]\"m\"

ls.str()

:

>ls.str()

m:num0.5n1:

num10n2:

num100name:

chr\"Carmen\"

patternmax.level,ls.str

ls.str

max.level=-1

>M<-data.frame(n1,n2,m)>ls.str(pat=\"M\")M:‘data.frame’:1obs.of$n1:num10$n2:num100$m:num0.5

>ls.str(pat=\"M\max.level=-1)M:‘data.frame’:1obs.of

3variables:

3variables:

rm(x,y).

x

y

rm:rm(x)rm(list=ls())

x,

ls()

:rm(list=ls(pat=\"^m\"))

rm

6

2.3

R

>?lm

lm()(

)

help(lm)

help(\"lm\")

>?*

Error:syntaxerror>help(\"*\")Arithmetic

package:baseRDocumentation

ArithmeticOperators...

(

(package)

)

Description:briefdescription.

Usage:forafunction,givesthenamewithallitsargumentsandthepossible

options(withthecorrespondingdefaultvalues);foranoperatorgivesthetypicaluse.Arguments:forafunction,detailseachofitsarguments.Details:detaileddescription.

Value:ifapplicable,thetypeofobjectreturnedbythefunctionortheoper-ator.SeeAlso:otherhelppagescloseorsimilartothepresentone.

Examples:someexampleswhichcangenerallybeexecutedwithoutopening

thehelpwiththefunctionexample.

Examples

Arguments

Note,ReferencesAuthor(s)help

FALSE,TRUE

try.all.package

7

>help(\"bs\")

Nodocumentationfor’bs’inspecifiedpackagesandlibraries:youcouldtry’help.search(\"bs\")’

>help(\"bsry.all.packages=TRUE)

Helpfortopic’bs’isnotinanyloadedpackagebutcanbefoundinthefollowingpackages:Packagesplines

Library

/usr/lib/R/library

bs

package

:

>help(\"bs\package=\"splines\")bspackage:splinesB-SplineBasisforPolynomialSplinesDescription:

RDocumentation

GeneratetheB-splinebasismatrixforapolynomialspline....

Html

>help.start()

html

SeeAlso

R

help.search

help.search(\"tree\")

“tree”

help.searchrebuild

help.search(\"tree\rebuild=TRUE))

apropos

(e.g.,

>apropos(help)[1]\"help\"

[4]\"help.start\"

\".helpForCall\"\"help.search\"

8

3R

3.1

R

{1,2,3}

R

7

(FALSE

TRUE)

modelength

>x<-1

>mode(x)

[1]\"numeric\">length(x)[1]1

>A<-\"Gomphotherium\";compar<-TRUE;z<-1i>mode(A);mode(compar);mode(z)[1]\"character\"[1]\"logical\"[1]\"complex\"

NA(

)

>N<-2.1e23>N

[1]2.1e+23

R)

Inf

-Inf

±∞

NaN(

7

9

>x<-5/0>x

[1]Inf>exp(x)[1]Inf>exp(-x)[1]0>x-x[1]NaN

\"

\\

write.table

(

p.14,

\\\"qmethod

cat

)

>x<-\"Doublequotes\\\"delimitateR’sstrings.\">x

[1]\"Doublequotes\\\"delimitateR’sstrings.\">cat(x)

Doublequotes\"delimitateR’sstrings.

(’)

>x<-’Doublequotes\"delimitateR\\’sstrings.’>x

[1]\"Doublequotes\\\"delimitateR’sstrings.\"

(ts)

...

10

k

k=2

ts

[2,2]

dim4

22

dim

3.2

R

getwd()()setwd(\"/home/-paradis/R\")

setwd(\"C:/data\")

8

R(

)scan

(Excel,SAS,SPSS,...)

ASCII

read.fwfRSQL

R

read.table

ASCII

read.table

data.dat

>mydata<-read.table(\"data.dat\")

mydata

V1,V2,...

mydata[\"V1\"],mydata[\"V2\"],...,mydata$V2,...,

mydata[,1],mydata[,2],...9

R)

mydata$V1,

(

read.table(file,header=FALSE,sep=\"\quote=\"\\\"’\dec=\".\row.names,col.names,as.is=FALSE,na.strings=\"NA\colClasses=NA,nrows=-1,

skip=0,check.names=TRUE,fill=!blank.lines.skip,

8

Windows

Rgui.exe

9

R

mydata$V1

mydata[,1]

mydata[\"V1\"]

(p.19)

11

strip.white=FALSE,blank.lines.skip=TRUE,comment.char=\"#\")

file

\"\"

WindowsURL

\\http://...

URL

headersepquotedec

row.namescol.namesas.is

(FALSEorTRUE)

sep=\"\\"

(

1,2,3,...)(V1,V2,V3,...)

(

TRUEas.is

FALSE)

na.strings

colClassesnrowsskip

check.namesfill

strip.whiteblank.lines.skipcomment.char

(

NA)

)

R

(

TRUETRUE

sep

TRUE

TRUE

comment.char=\"\"

read.table

read.csv(file,header=TRUE,sep=\quote=\"\\\"\dec=\".\

fill=TRUE,...)

read.csv2(file,header=TRUE,sep=\";\quote=\"\\\"\dec=\

fill=TRUE,...)

read.delim(file,header=TRUE,sep=\"\\quote=\"\\\"\dec=\".\

fill=TRUE,...)

read.delim2(file,header=TRUE,sep=\"\\quote=\"\\\"\dec=\

fill=TRUE,...)

scan

read.table

12

>mydata<-scan(\"data.dat\what=list(\"\0,0))

data.dat

scan()

...

what

mydata

scan()

scan(file=\"\what=double(0),nmax=-1,n=-1,sep=\"\

quote=if(sep==\"\\n\")\"\"else\"’\\\"\dec=\".\skip=0,nlines=0,na.strings=\"NA\

flush=FALSE,fill=FALSE,strip.white=FALSE,quiet=FALSE,blank.lines.skip=TRUE,multi.line=TRUE,comment.char=\"\")

file

\"\"/,http://...

(

),

\\

Windowsfile=””

URL

whatnmaxnsepquotedecskipnlinesna.stringflushfillstrip.whitequiet

blank.lines.skipmulti.linecomment.char

what

nmax

scan

(

)

NA

TRUE

scan

TRUE

sep

TRUE

TRUE

scan

TRUEwhat

FALSE

character

read.fwf

13

read.fwf(file,widths,sep=\"\\as.is=FALSE,

skip=0,row.names,col.names,n=-1,...)

widthsread.table()data.txt

A1.501.2A1.551.3B1.601.4B1.651.5C1.701.6C1.751.7

>mydata<-read.fwf(\"data.txt\widths=c(1,4,3))>mydataV1V2V31A1.501.22A1.551.33B1.601.44B1.651.55C1.701.66C1.751.7

3.3

write.table

...

write.table(x,file=\"\append=FALSE,quote=TRUE,sep=\"\

eol=\"\\n\na=\"NA\dec=\".\row.names=TRUE,col.names=TRUE,qmethod=c(\"escape\\"double\"))

14

xfileappendquote

TRUE

TRUE

\"\"

quote

\"\"

\"\"

quote=FALSE)

(

)

sepeolnadec

row.namescol.namesqmethod

(\"\\n\"

quote=TRUE

\"escape\"(

\"\"\"

\"

\"e\"

)

\"

\\\"

\"d\"

write(x,

file=\"data.txt\"),

x

nc(

x

append

ncol)

nc=1TRUE

nc=5

FALSE

save(x,y,z,

file=\"xyz.RData\")RData\")

file=\".RData\")

ASCII

TRUE

R

save.image()

load(\"xyz.

save(list=ls(all=TRUE),

3.4

3.4.1

130

>x<-1:30

x

30

‘:’

>1:10-1

[1]0123456789>1:(10-1)

[1]123456789

15

seq

>seq(1,5,0.5)

[1]1.01.52.02.53.03.54.04.55.0

>seq(length=9,from=1,to=5)

[1]1.01.52.02.53.03.54.04.55.0

c

>c(1,1.5,2,2.5,3,3.5,4,4.5,5)[1]1.01.52.02.53.03.54.04.55.0

scan

>z<-scan()

1:1.01.52.02.53.03.54.04.55.010:

Read9items>z

[1]1.01.52.02.53.03.54.04.55.0

rep

>rep(1,30)

[1]111111111111111111111111111111

sequence

>sequence(4:5)

[1]123412345>sequence(c(10,5))[1]123456

7

8

910

1

2

3

4

5

gl(

/)gl(k,n)

k

length

n

labels

16

>gl(3,5)

[1]111112222233333Levels:123

>gl(3,5,length=30)

[1]111112222233333111112222233333Levels:123

>gl(2,6,label=c(\"Male\\"Female\"))[1]MaleMaleMaleMaleMaleMale[7]FemaleFemaleFemaleFemaleFemaleFemaleLevels:MaleFemale>gl(2,10)

[1]11111111112222222222Levels:12

>gl(2,1,length=20)

[1]12121212121212121212Levels:12

>gl(2,2,length=20)

[1]11221122112211221122Levels:12

expand.grid()

>expand.grid(h=c(60,80),w=c(100,300),sex=c(\"Male\\"Female\"))

hwsex160100Male280100Male360300Male480300Male560100Female680100Female760300Female880300Female

17

3.4.2

Gaussian(normal)exponentialgammaPoissonWeibullCauchybeta

‘Student’(t)

Fisher–Snedecor(F)Pearson(χ2)binomialmultinomialgeometric

hypergeometriclogisticlognormal

negativebinomialuniform

Wilcoxon’sstatisticsrnorm(n,mean=0,sd=1)rexp(n,rate=1)

rgamma(n,shape,scale=1)rpois(n,lambda)

rweibull(n,shape,scale=1)

rcauchy(n,location=0,scale=1)rbeta(n,shape1,shape2)rt(n,df)

rf(n,df1,df2)rchisq(n,df)

rbinom(n,size,prob)rmultinom(n,size,prob)rgeom(n,prob)

rhyper(nn,m,n,k)

rlogis(n,location=0,scale=1)rlnorm(n,meanlog=0,sdlog=1)rnbinom(n,size,prob)runif(n,min=0,max=1)

rwilcox(nn,m,n),rsignrank(nn,n)R

rfunc(n,p1,p2,...)p1,p2,...

func

n

d

p

q

...))

(dfunc(x,...))

(qfunc(p,...)

P

r

(pfunc(x,

05%

>qnorm(0.025)[1]-1.959964>qnorm(0.975)[1]1.959964

qnorm(0.05)

1-

qnorm(0.95)

18

P

df=1χ2=3.84

>1-pchisq(3.84,1)[1]0.05004352

3.5

3.5.1

c()

(p.27)

lm

R

Vector

vector

(mode)

(length)

\"\"

0

FALSE

numeric()

logical()

character()

Factor

factor

factor(x,levels=sort(unique(x),na.last=TRUE),

labels=levels,exclude=NA,ordered=is.ordered(x))levels

x

exclude

x

labelsordered

x

>factor(1:3)[1]123

19

Levels:123

>factor(1:3,levels=1:5)[1]123

Levels:12345

>factor(1:3,labels=c(\"A\\"B\\"C\"))[1]ABC

Levels:ABC

>factor(1:5,exclude=4)[1]123NA5Levels:1235

levels

>ff<-factor(c(2,4),levels=2:5)>ff[1]24

Levels:2345>levels(ff)

[1]\"2\"\"3\"\"4\"\"5\"

Matrix

dim

2

matrix

matrix(data=NA,nrow=1,ncol=1,byrow=FALSE,

dimnames=NULL)

byrow

TRUE

dimnames

>matrix(data=5,nr=2,nc=2)

[,1][,2][1,]55[2,]55

>matrix(1:6,2,3)

[,1][,2][,3][1,]135[2,]246

>matrix(1:6,2,3,byrow=TRUE)

[,1][,2][,3][1,]123[2,]456

20

NULL

>x<-1:15>x

[1]123456789101112131415

>dim(x)NULL

>dim(x)<-c(5,3)>x

[,1][,2][,3][1,]1611[2,]2712[3,]3813[4,]4914[5,]51015Dataframetable

data.frame

>x<-1:4;n<-10;M<-c(10,35);y<-2:4

>data.frame(x,n)xn1110221033104410

>data.frame(x,M)xM1110223533104435

>data.frame(x,y)

Errorindata.frame(x,y):

argumentsimplydifferingnumberofrows:4,3

data.frame(A1=x,A2=n)

21

read.

row.names

List

list

data.frame()

x

y

>L1<-list(x,y);L2<-list(A=x,B=y)

>L1[[1]]

[1]1234[[2]]

[1]234>L2$A

[1]1234$B

[1]234>names(L1)NULL

>names(L2)[1]\"A\"\"B\"

Time-series

ts

ts

ts(data=NA,start=1,end=numeric(0),frequency=1,

deltat=1,ts.eps=getOption(\"ts.eps\"),class,names)

22

datastartend

frequencydeltat

start

1/12

frequency

deltat

ts.epsclassnames

ts.eps

\"ts\"

c(\"mts\\"ts\")

data

Series1,

Series2,...

ts

>ts(1:10,start=1959)TimeSeries:Start=1959End=1968Frequency=1

[1]12345678910

>ts(1:47,frequency=12,start=c(1959,2))

JanFebMarAprMayJunJulAugSepOctNovDec19591234567891011196012131415161718192021222319612425262728293031323334351962363738394041424344454647>ts(1:10,frequency=4,start=c(1959,2))

Qtr1Qtr2Qtr3Qtr419591231960456719618910

>ts(matrix(rpois(36,5),12,3),start=c(1961,1),frequency=12)

Series1Series2Series3

Jan1961854Feb1961669Mar1961233

23

AprMayJunJulAugSepOctNovDec196119611961196119611961196119611961Expression

84441166585962655554313647772R

R

expresssion

eval()

>x<-3;y<-2.5;z<-1

>exp1<-expression(x/(y+exp(z)))>exp1

expression(x/(y+exp(z)))>eval(exp1)[1]0.5749019

(p.43)

D

>D(exp1,\"x\")1/(y+exp(z))>D(exp1,\"y\")-x/(y+exp(z))^2>D(exp1,\"z\")

-x*exp(z)/(y+exp(z))^23.5.2

R

2.1.0

baseutils

as.something

98

24

as.numeric

as.logical

FALSE

TRUE

\"1\",\"2\",...

\"A\",...

0

\"FALSE\",\"F\"\"TRUE\",\"T\"

as.character

1,2,...FALSETRUE

→→→→→→→→→→→→01

1,2,...NAFALSETRUEFALSETRUENA

\"1\",\"2\",...\"FALSE\"\"TRUE\"

(as.matrix,as.ts,as.data.frame,

as.expression,...)

R

R

>fac<-factor(c(1,10))>fac[1]110

Levels:110

>as.numeric(fac)[1]12

>fac2<-factor(c(\"Male\\"Female\"))>fac2[1]MaleFemaleLevels:FemaleMale>as.numeric(fac2)[1]21

NA

25

>as.numeric(as.character(fac))[1]110

read.table()

3.5.3

10

R+

x&y*<=x&&y/>=x|y^==x||y

%%!=

xor(x,y)

%/%

(x+y,a(

!

)

&

|&&

||

0001(TRUEFALSE<1)

(1

0<1)

>x<-0.5>010

R

$,@,[,[[,:,?,<-,<<-,=,::

?Syntax

26

0identical

all.equal

>x<-1:3;y<-1:3>x==y

[1]TRUETRUETRUE>identical(x,y)[1]TRUE

>all.equal(x,y)[1]TRUE

identical

FALSEall.equalTRUE

>0.9==(1-0.1)[1]TRUE

>identical(0.9,1-0.1)[1]TRUE

>all.equal(0.9,1-0.1)[1]TRUE

>0.9==(1.1-0.2)[1]FALSE

>identical(0.9,1.1-0.2)[1]FALSE

>all.equal(0.9,1.1-0.2)[1]TRUE

>all.equal(0.9,1.1-0.2,tolerance=1e-16)[1]\"Meanrelativedifference:1.233581e-16\"3.5.4

x

x[3]

>x<-1:5

>x[3][1]3

>x[3]<-20

27

TRUE

3

>x[1]

122045

>i<-c(1,3)>x[i][1]120

x

i

j

x[i,j]

>x<-matrix(1:6,2,3)>x

[,1][,2][,3][1,]135[2,]246>x[,3]<-21:22>x

[,1][,2][,3][1,]1321[2,]2422>x[,3][1]2122

R

drop

TRUE:

>x[,3,drop=FALSE]

[,1][1,]21[2,]22

x[i,j,k],x[,,3],x[,,3,drop=FALSE]

>x(1)

Error:couldn’tfindfunction\"x\"

28

x[-1,

]

x[-c(1,15),]

1

15

>x[,-1]

[,1][,2][1,]321[2,]422>x[,-(1:2)][1]2122

>x[,-(1:2),drop=FALSE]

[,1][1,]21[2,]22

>x<-1:10>x[x>=5]>x

[1]12>x[x==1]>x

[1]252

<-20

34202020202020<-253

4202020202020

>x<-rpois(40,lambda=5)>x

[1]59477645113[21]4665453433>x[x%%2==0]

[1]464222466448424

53771753389124225124

>x<-1:40

>s<-c(FALSE,TRUE)>x[s]

[1]246810121416182022242628303234363840

29

3

my.list[[3]][i]

my.list[[3]][i,j,k]

12

my.list[1:2]

my.list[[1:2]]

3.5.5

names(names,colnames,rownames,dimnames)

names

>x<-1:3

>names(x)NULL

>names(x)<-c(\"a\\"b\\"c\")>xabc123

>names(x)

[1]\"a\"\"b\"\"c\">names(x)<-NULL>x

[1]123

colnames

rownamesdimnames

>X<-matrix(1:4,2)

>rownames(X)<-c(\"a\\"b\")>colnames(X)<-c(\"c\\"d\")>

Xcda13b24

>dimnames(X)

30

names

[[1]]

[1]\"a\"\"b\"[[2]]

[1]\"c\"\"d\"

dimnames

>A<-array(1:8,dim=c(2,2,2))>A,,1

[,1][,2][1,]13[2,]24,,2

[,1][,2][1,]57[2,]68

>dimnames(A)<-list(c(\"a\\"b\"),c(\"c\\"d\"),c(\"e\\"f\"))>A,,ecda13b24,,fcda57b68

DF[\"x\"]

x

DF

DF[c(\"x\\"y\")]

x

y

z

31

$(

DF$x)

3.5.6

X

data.entry(X)

data.entry

de

3.5.7

R

c

>c(1:5,seq(10,11,0.2))

[1]1.02.03.04.05.010.010.210.410.610.811.0

>x>y>z>z[1]

<-1:4

<-rep(1,4)<-x+y2345

>x>y>z>z[1]>x>y

<-1:4<-1:2<-x+y2446<-1:3<-1:2

32

>z<-x+y

Warningmessage:longerobjectlength

isnotamultipleofshorterobjectlengthin:x+y>z

[1]244

R

>x>a>z>z[1]

<-1:4<-10<-a*x10203040R

abs,sqrt,...),

(log,exp,log10,log2,sin,cos,tan,asin,acos,atan,

(gamma,digamma,beta,besselI,...)

sum(x)prod(x)max(x)min(x)

which.max(x)which.min(x)range(x)length(x)mean(x)median(x)

var(x)orcov(x)cor(x)

var(x,y)orcov(x,y)cor(x,y)

xx

xx

xx

c(min(x),max(x))

xxxx

n−1

x

x

xxy

1

x

y

x

y

(

1

)

range

33

2

var,cov,

cor

round(x,n)rev(x)sort(x)rank(x)

log(x,base)scale(x)

xxx

n

rev(sort(x))

x

base

x

x

pmin(x,y,...)pmax(x,y,...)cumsum(x)cumprod(x)cummin(x)cummax(x)match(x,y)which(x==a)

center=FALSE

center=TRUE,scale=TRUE

i

scale=FALSE

x[i],y[i],...x[1]

x[i]

i

x

x

y

y

NA

x

TRUE

i

x[i]==a

choose(n,k)na.omit(x)na.fail(x)unique(x)table(x)table(x,y)subset(x,...)

n

k

NA

x

xx

NA

x

(

)

(...

x

y

x

x$V1<10

x

select

sample(x,size)

size

replace=TRUE

3.5.8

R

rbind()

cbind()

>m1<-matrix(1,nr=2,nc=2)

34

>m2<-matrix(2,nr=2,nc=2)>rbind(m1,m2)

[,1][,2][1,]11[2,]11[3,]22[4,]22>cbind(m1,m2)

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

%*%

>rbind(m1,m2)%*%cbind(m1,m2)

[,1][,2][,3][,4][1,]2244[2,]2244[3,]4488[4,]4488

>cbind(m1,m2)%*%rbind(m1,m2)

[,1][,2][1,]1010[2,]1010

t

diag

>diag(m1)[1]11

>diag(rbind(m1,m2)%*%cbind(m1,m2))[1]2288

>diag(m1)<-10>m1

[,1][,2][1,]101[2,]110>diag(3)

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

35

m1

m2

[2,]010[3,]001>v<-c(10,20,30)>diag(v)

[,1][,2][,3][1,]1000[2,]0200[3,]0030

>diag(2.1,nr=3,nc=5)

[,1][,2][,3][,4][,5][1,]2.10.00.000[2,]0.02.10.000[3,]0.00.02.100

R

qr

eigen

36

solve

svd

4

R

R

demo(persp)

:demo(graphics)

R

11

graphicaldevice

high-levelplottingfunctions

low-levelplottingfunctionsgraphicalparameters

par

grid

lattice

4.1

4.1.1

R

Unix/Linux

x11

Windows

windows

Windows

x11()

windows()postscript(),

pdf(),png(),...

?device

dev.list()

>x11();x11();pdf()>dev.list()X11X11pdf234

11

:hist()

barplot()

37

>dev.cur()pdf4

>dev.set(3)X113

dev.off()

R

>dev.off(2)X113

>dev.off()pdf4

R

Widows

win.metafile

“History”

“Recording”

WindowsMetafile

4.1.2

split.screen

>split.screen(c(1,2))

screen(1)

screen(2)erase.screen()

split.screen()

layout()

coplot()

layout

“sub-windows”

4

>layout(matrix(1:4,2,2))

38

>mat<-matrix(1:4,2,2)>mat

[,1][,2][1,]13[2,]2>layout(mat)

4

layout.show

4

13

>layout.show(4)

2

4

layout()

>layout(matrix(1:6,3,2))>layout.show(6)

123

456

>layout(matrix(1:6,2,3))>layout.show(6)

135

246

>m<-matrix(c(1:3,3),2,2)>layout(m)

>layout.show(3)

1

3

2

matrix()byrow

matrix(...,byrow=TRUE)

matrix(c(2,1,4,3),

2,2)

layout()widths

heights

(

?layout)

>m<-matrix(1:4,2,2)>layout(m,widths=c(1,3),

heights=c(3,1))

>layout.show(4)

39

13

24

>m<-matrix(c(1,1,2,1),2,2)>layout(m,widths=c(2,1),

heights=c(1,2))

>layout.show(2)

2

1

0

>m<-matrix(0:3,2,2)

>layout(m,c(1,3),c(1,3))>layout.show(3)

>m<-matrix(scan(),5,5)1:003331133311:003330220521:4220526:

Read25items>layout(m)

>layout.show(5)

2

13

1

4

2

3

5

40

4.2

R

:

plot(x)plot(x,y)

sunflowerplot(x,y)

pie(x)

boxplot(x)stripchart(x)coplot(x~y|z)interaction.plot(f1,f2,y)matplot(x,y)dotchart(x)

fourfoldplot(x)assocplot(x)mosaicplot(x)pairs(x)plot.ts(x)ts.plot(x)hist(x)barplot(x)qqnorm(x)qqplot(x,y)

contour(x,y,z)

x-x(x-)

x(y-y(y-)

)

x

(“box-and-whiskers”)(boxplot())zxyf1f2f1x-yy-fun

fun=meanxyx

f2

y

y

x

Cleveland

x

dim=c(2,

2,k)

Cohen–Friendly‘mosaic’

xx\"ts\"

dim=c(2,2)

k=1

x

x

x

x

xx

x

x

y

xy

dim(z)=c(length(x),length(y))x

z

y

filled.contour(x,y,z)

image(x,y,z)persp(x,y,z)stars(x)

symbols(x,y,...)termplot(mod.obj)

x

x

x

y

“boxplots”

mod.obj

41

R

add=FALSEaxes=TRUEtype=\"p\"

TRUEFALSE

\"p\":

\"l\":

\"h\":\"S\":

\"b\":\"s\":

\"o\":

xlim=,ylim=xlab=,ylab=main=sub=

xlim=c(1,10)

xlim=range(x)

4.3

R

(low-levelplottingcommands)

:

points(x,y)lines(x,y)

text(x,y,labels,...)

mtext(text,

side=3,line=0,...)

segments(x0,y0,x1,y1)

arrows(x0,y0,

x1,y1,angle=30,code=2)

abline(a,b)abline(h=y)abline(v=x)abline(lm.obj)rect(x1,y1,x2,y2)

polygon(x,y)legend(x,y,legend)title()

axis(side,vect)

type=

(x,y)labels

type=\"n\");text(x,y,names)

text

axis()line

:plot(x,y,

side

(x0,y0)

(x1,y1)

code=2

(x1,y1)

(x0,y0)

code=3;angle

code=1

b

a

y

abcissaxlm.obj

x1,x2,y1,

y2

x

y

(x,y)

legend

(side=1)vect

(2)

abcissa

(3)

(4)

42

box()rug(x)

locator(n,

type=\"n\...)

x-

x

(...)

(type=\"n\")

n

(type=\"p\")

(x,y)

(type=\"l\")

text(x,y,expression(...))expression

>text(x,y,expression(p==over(1,1+e^-(beta*x+alpha))))

(x,y)

:

p=

1+e−(βx+α)

1

R2

Rsquared

>text(x,y,as.expression(substitute(R^2==r,list(r=Rsquared))))

(x,y)

R2=0.9856298

3

>text(x,y,as.expression(substitute(R^2==r,+list(r=round(Rsquared,3)))))

R2=0.986

R

>text(x,y,as.expression(substitute(italic(R)^2==r,+list(r=round(Rsquared,3)))))

R2=0.986

43

4.4

par

>par(bg=\"yellow\")

73

?par

adj

0

0.5

1

>1

c(0,0))

bgbtycexcolfontlaslty

bg=\"red\",bg=\"blue\";

colors()

657

:\"o\",\"l\",\"7\",\"c\",\"u\"ou\"]\"

bty=\"n\"

cex.labcex.maincex.subcexcol.axis,col.lab,col.main,col.sub1:2:3:4:cex

font.axis,font.lab,font.main,font.sub

0:1:2:3:

1:2:3:4:5:

6:8\"0\"\"9\"

lty=\"44\"lty=2

cex.axis

:

lwdmarmfcolmfrowpchpsptytcktclxaxtyaxt

4

c(5.1,4.1,4.1,2.1)

c(nr,nc)4.1.2

c(bottom,left,top,right),

nr

nc

4.1.2

125

\"\"

2

\"s\":

\"m\":

tck=1

xaxt=\"n\"yaxt=\"n\"

x-y-

tcl=-0.5

axis(side=1,...)axis(side=2,...)

44

12345678910

111213141516171819202122232425

\"*\"

\"?\"\".\"\"X\"\"a\"

*

Figure2:

?

Xa

R(pch=1:25)

21–25

col=\"blue\bg=\"yellow\"

pch=\"*\",

\"?\",\".\",...

4.5

R

10

>x<-rnorm(10)>y<-rnorm(10)

plot()

>plot(x,y)

3

R

plot(x,y,xlab=\"Tenrandomvalues\ylab=\"Tenothervalues\

xlim=c(-2,2),ylim=c(-2,2),pch=22,col=\"red\bg=\"yellow\bty=\"lcl=0.4,

main=\"HowtocustomizeaplotwithR\las=1,cex=1.5)

45

y−1.0−0.5

−0.50.00.50.0

x

0.51.0

Figure3:

plot

4

xlab

ylab

xlim

12

pch

ylimpch=22

col

bg

bty,tcl,las

cex

main

plot

par()

5

opar<-par()par(bg=\"lightyellow\col.axis=\"blue\mar=c(4,4,2.5,0.25))plot(x,y,xlab=\"Tenrandomvalues\ylab=\"Tenothervalues\

xlim=c(-2,2),ylim=c(-2,2),pch=22,col=\"red\bg=\"yellow\bty=\"lcl=-.25,las=1,cex=1.5)

title(\"HowtocustomizeaplotwithR(bis)\font.main=3,adj=1)par(opar)

opar

bg

col.axis

mar

12

xaxs=\"i\"

R

yaxs=\"i\"

4%plot()

46

How to customize a plot with R

2

1Ten other values0

−1

−2

−2

−1

0

Ten random values

1

2

Figure4:

plot

How to customize a plot with R (bis)21Ten other values0−1−2−2−10Ten random values12Figure5:

par

plot

title

47

4title

5

R

plot(...,type=\"n\")

6

opar<-par()par(bg=\"lightgray\mar=c(2.5,1.5,2.5,0.25))plot(x,y,type=\"n\xlab=\"\ylab=\"\xlim=c(-2,2),

ylim=c(-2,2),xaxt=\"n\yaxt=\"n\")

rect(-3,-3,3,3,col=\"cornsilk\")points(x,y,pch=10,col=\"red\cex=2)axis(side=1,c(-2,0,2),tcl=-0.2,labels=FALSE)

axis(side=2,-1:1,tcl=-0.2,labels=FALSE)title(\"HowtocustomizeaplotwithR(ter)\

font.main=4,adj=1,cex.main=1)

mtext(\"Tenrandomvalues\side=1,line=1,at=1,cex=0.9,font=3)mtext(\"Tenothervalues\line=0.5,at=-1.8,cex=0.9,font=3)mtext(c(-2,0,2),side=1,las=1,at=c(-2,0,2),line=0.3,

col=\"blue\cex=0.9)

mtext(-1:1,side=2,las=1,at=-1:1,line=0.2,col=\"blue\cex=0.9)par(opar)

type=\"n\"

xaxt=\"n\yaxt=\"n\"

xlimylim

xlab=\"\

axes=FALSE

rect()

points()

axis()

labels=FALSE

labels=c(\"A\\"B\

\"C\")

title()

mtext()

line

mtext()side(3)

line=0

mtext()

at

48

Ten other valuesHow to customize a plot with R (ter)10−1−20Ten random values2Figure6:

4.6grid

lattice

gridandlattice

••

viewports

(grob)

gridBase

R

S-PLUS

Trellis

Trellis

13

Trellis

coplot

latticey~x

14

y~x|z

y

x

z

http://cm.bell-labs.com/cm/ms/departments/sia/project/trellis/index.htmlplot()xyplot(y~x)plot(x,y)

14

13

49

lattice

(y~x|z)

z

barchart(y~x)bwplot(y~x)densityplot(~x)dotplot(y~x)histogram(~x)qqmath(~x)

stripplot(y~x)qq(y~x)

xyplot(y~x)

levelplot(z~x*y)contourplot(z~x*y)cloud(z~x*y)

wireframe(z~x*y)splom(~x)parallel(~x)

x

y

Clevelandx

(

)

x

x

y

x

y

”y

z

z

x

y

x

3-D

lattice

library(lattice)

densityplot(~x)

x-

rug()

panel

n<-seq(5,45,5)x<-rnorm(sum(n))y<-factor(rep(n,n),labels=paste(\"n=\n))densityplot(~x|y,

panel=function(x,...){

panel.densityplot(x,col=\"DarkOliveGreen\...)panel.mathdensity(dmath=dnorm,

args=list(mean=mean(x),sd=sd(x)),col=\"darkblue\")

})

45

densityplot

5,10,15,...,panel

panel.densityplot

lattice

panel.mathdensity

panel.densityplot

50

−4−2024n = 350.60.50.40.30.20.10n = 40n = 45n = 20n = 25n = 300.60.5Density0.40.30.20.10n = 50.60.50.40.30.20.10−4−2024n = 10n = 15−4−2024xFigure7:

densityplot

panel

densityplot(~x|y)

7

lattice

R

1000

8

data(quakes)mini<-min(quakes$depth)maxi<-max(quakes$depth)int<-ceiling((maxi-mini)/9)inf<-seq(mini,maxi,int)

quakes$depth.cat<-factor(floor(((quakes$depth-mini)/int)),

labels=paste(inf,inf+int,sep=\"-\"))

xyplot(lat~long|depth.cat,data=quakes)

(

quakesdepth)

5

data

xyplot

xyplot

15

iris

9

data(iris)xyplot(

Petal.Length~Petal.Width,data=iris,groups=Species,panel=panel.superpose,

plot()~quakes$lat)

15

data

,

plot(quakes$long

51

165170175180185472−544−10−15−20−25−30−35−40544−616616−688256−328328−400400−472−10−15t−20al−25−30−3540−112112−184184−256−40−10−15−20−25−30−35−40165170175180185165170175180185longFigure8:

quakes

xyplot

type=c(\"p\\"smooth\"),span=.75,auto.key=list(x=0.15,y=0.85))

xyplotgroupspanel

panel.superpose

panel.superposetypeplot()

\"p\"

\"smooth\"

spanauto.key

[0,1]

splom

iris

10

splom(

~iris[1:4],groups=Species,data=iris,xlab=\"\panel=panel.superpose,

auto.key=list(columns=3))

iris

pairs

splom“ScatterPlotMatrix”

xlab=\"\"

52

x-7ooooooooooooooooooooooooooooo6setosaversicolorvirginicaoooooooooooooooooooo5oooooooooooooooooooPetal.Length4ooooooooooo3o2oo1oooooooooooooooooooo00.511.522.5Petal.WidthFigure9:

iris

xyplot

SetosaooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooVersicolorVirginicaoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo2.521.51.522.5Petal.Width10.5ooooooooooooooooooooooooooooooooooooooo0oooooooooooo7oo4567oooooooooooooooo6oooooooooooooooooooooooooooooooooooooooooooooo5oooooooooooooooooooooooooooooooooooooooooooooooooooooooooo4Petal.Length4oooooooooooooooooooo3ooo4.543.5oooooooooooooooooooo1oooooo3.54223410.510ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo8787ooooooooooooooooooooooooooooooooooooooooooSepal.Width4.5ooooooooooooooooooooooooooooooooo3oo2.5o22.532Sepal.Length6556oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooFigure10:

iris

1

splom

53

virginicaPetalLengthSepalWidthSepalLengthsetosaPetalLengthversicolorPetalLengthSepalWidthSepalWidthSepalLengthSepalLengthScatter Plot MatrixFigure11:

iris

2

splom

auto.key

columns=3

3

10

pairs()

Fig.11

splom(~iris[1:3]|Species,data=iris,pscales=0,

varnames=c(\"Sepal\\nLength\\"Sepal\\nWidth\\"Petal\\nLength\"))

pscales=

0

\"\\n\"

y-

iris

12

parallel(~iris[,1:4]|Species,data=iris,layout=c(3,1))

54

MinMaxsetosaPetal.WidthversicolorvirginicaPetal.LengthSepal.WidthSepal.LengthMinMaxMinMaxFigure12:

iris

parallel

55

5R

R

.

R

.

stats,

,

(

,

,

),

,

.

,

R

,

.

R

,

.stats,

R

,

,

(formulae).

(genericfunctions).

5.1

stats

:InsectSprays.

.

aov.

,

R

,.

12

,

72

,

.

data

,

:

>data(InsectSprays)

>aov.spray<-aov(sqrt(count)~spray,data=InsectSprays)

aov

(~

InsectSprays

)

.

.

data=InsectSprays

.

:

>aov.spray<-aov(sqrt(InsectSprays$count)~InsectSprays$spray)

,

:

>aov.spray<-aov(sqrt(InsectSprays[,1])~InsectSprays[,2])

,

,

.

56

,

aov.spray.

,

(

),

printsummary

(

):

>aov.sprayCall:

aov(formula=sqrt(count)~spray,data=InsectSprays)Terms:

sprayResiduals

SumofSquares88.4378726.05798Deg.ofFreedom

5

66

Residualstandarderror:0.6283453Estimatedeffectsmaybeunbalanced

>summary(aov.spray)

DfSumSqMeanSqFvaluePr(>F)

spray588.43817.68844.799<2.2e-16***Residuals26.0580.395---Signif.codes:0‘***’0.001‘**’0.01‘*’0.05‘.’0.1‘’1

print(aov.spray)

.plot()termplot()

.

plot(aov.spray),

,

16.

:

>opar<-par()

>par(mfcol=c(2,2))>plot(aov.spray)>par(opar)

>termplot(aov.spray,se=TRUE,partial.resid=TRUE,rug=TRUE)

13

14

.

5.2

17R

:

.

y~model,

y

,model

16

17

:

layout

:

,

.

57

66

Standardized residualsResiduals vs Fitted

Residuals1.02739

Scale−Location plot

1.5272539

0.0−1.5251.52.5Fitted values

3.5

0.01.5

0.51.02.5Fitted values

3.5

Standardized residualsNormal Q−Q plot

0.08Cook’s distance23927Cook’s distance plot

272539125−2−1012

0.000

−20.040204060

Theoretical QuantilesObs. number

Figure13:

plot()

aov

.

.

.

bX,,X[,1]+X[,2]+...+X[,ncol(X)];

(,X[,2:4])

ab

(a+b+a:b)

an

,n,(a+b+c)^2

a+b+c+a:b+a:c+b:c

(a+a:b,a/b)ba

b,:(a+b+c)^2-a:b

a+b+c+a:c+b:c

(y~x+0y~x-1

0+y~x)

()y~1

(

offset(3*x))a

a+bX

a:ba*b

poly(a,n)^nb%in%a-b-1

1

offset(...)

,.

R

,

,

+

,

y~x1+x2y=β1x1+β2x2+α,()y=β(x1+x2)+α.

I:y~I(x1+x2)y=β(x1+x2)+α.

58

Partial for spray−30

−2−1012123spray

456

Figure14:

termplot()

aov

.

(

y=β1x+β2x2+α,

y~x+x^2).,,

y~poly(x,2)

,

.

+Error(b)

,aov()

a

.

,y~a

b

.

5.3

,R

\"aov\"

,lm

.

.R\"lm\"

.

(,aov

).

,

.

(

),

(generic)18.Rsummary.

\"lm\"(.

)

\"aov\"

19.

,

.

20.

R

21

.

18

:Java,C++.,R19

:Java

20

:.

21

R100

,

.

,

,

Java

.

.

.

59

.

:

>mod<-lm(y~x)>df.residual(mod)[1]8

printsummary

df.residualcoef

residualsdeviancefittedlogLikAIC

(

)

Akaike

(Akaikeinformationcriterion,AIC)(

logLik())

aov

lm:

.

InsectSprays

,

aov

>str(aov.spray,max.level=-1)Listof13

-attr(*,\"class\")=chr[1:2]\"aov\"\"lm\"

:

>names(aov.spray)[1]\"coefficients\"[4]\"rank\"[7]\"qr\"

[10]\"xlevels\"

\"residuals\"

\"fitted.values\"\"df.residual\"\"call\"

:

\"effects\"\"assign\"\"contrasts\"

\"terms\"[13]\"model\"

>aov.spray$coefficients(Intercept)sprayBsprayC3.76067840.1159530-2.5158217

sprayEsprayF-1.95121740.2579388

sprayD

-1.5963245

aov()

summary()

:

60

>str(summary(aov.spray))Listof1

$:Classesanovaand‘data.frame’:2obs.of5variables:..$Df:num[1:2]566

..$SumSq:num[1:2]88.426.1

..$MeanSq:num[1:2]17.6880.395..$Fvalue:num[1:2]44.8NA..$Pr(>F):num[1:2]0NA

-attr(*,\"class\")=chr[1:2]\"summary.aov\"\"listof\">names(summary(aov.spray))NULL

:

.

R

,

generic.cls,

:

cls

(method).,.,summary

,

>apropos(\"^summary\")

[1]\"summary\"\"summary.aov\"[3]\"summary.aovlist\"\"summary.connection\"[5]\"summary.data.frame\"\"summary.default\"[7]\"summary.factor\"\"summary.glm\"[9]\"summary.glm.null\"\"summary.infl\"[11]\"summary.lm\"\"summary.lm.null\"[13]\"summary.manova\"\"summary.matrix\"[15]\"summary.mlm\"

\"summary.packageStatus\"[17]\"summary.POSIXct\"\"summary.POSIXlt\"[19]\"summary.table\"

,

:

>x<-y<-rnorm(5);>lm.spray<-lm(y~x)>names(lm.spray)

[1]\"coefficients\"\"residuals\"[4]\"rank\"\"fitted.values\"[7]\"qr\"\"df.residual\"[10]\"call\"\"terms\">names(summary(lm.spray))[1]\"call\"\"terms\"[4]\"coefficients\"\"sigma\"

61

\"effects\"\"assign\"\"xlevels\"\"model\"\"residuals\"\"df\"

[7]\"r.squared\"[10]\"cov.unscaled\"

\"adj.r.squared\"\"fstatistic\"

,

update

,

,

predict

.

add1drop1stepanovapredictupdate

AIC(

add1

drop1)

/

,

alias

,

,

plot

,

(

),

.

termplotpredict.

5.4

R

.

R

;

search

:

>search()

[1]\".GlobalEnv\"\"package:methods\"[3]\"package:stats\"\"package:graphics\"[5]\"package:grDevices\"\"package:utils\"[7]\"package:datasets\"\"Autoloads\"[9]\"package:base\"

:

>library(grid)

:

>library(help=grid)

.

(7)

.

62

basedatasetsgrDevicesgraphicsgridmethodssplinesstatsstats4tcltktoolsutils

RR

R

RR

S4

Tcl/Tk

R

.

R.

CRAN

22

.

,

.

R

.

.

bootclassclusterforeignKernSmoothlatticeMASSmgcvnlmennetrpartspatialsurvival

22

bootstraping

(S3,Stata,SAS,Minitab,SPSS,EpiInfo)(

)

Venables&Ripley

,

“ModernAppliedStatisticswithS”

,

(“kriging”,

,...)

http://cran.r-project.org/src/contrib/PACKAGES.html

63

R

:Omegahat

23

R

(

,Bioconductor).

CRAN“Packages”

24

)

(

R

.,

.Windows,Rgui.exe

.

R,(

.gee,

4.13-6;CRAN,

(R):

,

‘.tar.gz’

gee4.13-6.tar.gz

).,

RCMDINSTALLgee_4.13-6.tar.gz

,

installed.

download.packages.

packages,CRAN.packages,

:

>update.packages()

,

“Packages”.

CRAN

).

(Windows

2324

http://www.omegahat.org/R/http://www.bioconductor.org/

64

6R

,

.

R

,

R

.

6.1

,R

.

,

R

.

x,

,

x

1.

,Rb

C

.

,

0

y

x

y:

y<-numeric(length(x))for(iin1:length(x))if(x[i]==b)y[i]<-0elsey[i]<-1

:

for(iin1:length(x)){

y[i]<-0...}

if(x[i]==b){

y[i]<-0...}

:

while(myfun>minimum){

...}

,

R

,

:

.

,

.

,

:

65

>z<-x+y

,

:

>z<-numeric(length(x))

>for(iin1:length(z))z[i]<-x[i]+y[i]

,

,

z.

,

x

y

:

,

25.

(if...else)

;

:

>y[x==b]<-0>y[x!=b]<-1

,

,

.

‘apply’

X,FUN26),...

/,,MARGIN

(FUN

(1)

.apply

apply(X,MARGIN,FUN,...),

(2),(c(1,2))

,

.

.

>

>>>

x<-rnorm(10,-5,0.1)y<-rnorm(10,5,2)

XX<-cbind(x,y)#

apply(X,2,mean)

xy

-4.9751324.932979>apply(X,2,sd)

xy

0.07551532.1388071

\"x\"

\"y\"

lapply().

:

apply

>forms<-list(y~x,y~poly(x,2))>lapply(forms,lm)[[1]]

:R:

withinbrackets”

2526

,

,.

“oranoperator,butinthiscaseitmustbespecified

66

Call:FUN(formula=X[[1]])Coefficients:(Intercept)

x

31.6835.377

[[2]]

Call:FUN(formula=X[[2]])Coefficients:(Intercept)poly(x,2)1

poly(x,2)2

4.93301.2181

-0.6037

sapply()

lapply()

,

,

,

6.2

R

,

R

ASCII

,

‘.R’.

,

R

.

,

R

.

,

,

layout(matrix(1:3,3,1))

#data<-read.table(\"Swal.dat\")#plot(data$V1,data$V2,type=\"l\")title(\"swallow\")

#

data<-read.table(\"Wren.dat\")plot(data$V1,data$V2,type=\"l\")title(\"wren\")

data<-read.table(\"Dunn.dat\")plot(data$V1,data$V2,type=\"l\")title(\"dunnock\")

‘#’

:R.

,

,

,

,

.

67

.

,

..

.

,.

layout(matrix(1:3,3,1))#species<-c(\"swallow\\"wren\\"dunnock\")

file<-c(\"Swal.dat\",\"Wren.dat\\"Dunn.dat\")for(iin1:length(species)){

data<-read.table(file[i])#plot(data$V1,data$V2,type=\"l\")title(species[i])#}

read.table().

..

‘.dat’

,

data/Swal.dat\").

:

file[i]

,

,

R

,

(:file<-\"/home/paradis/Mybirds.R,

,

>source(\"Mybirds.R\")

,

,

.

6.3

R

,

.

,

R

.

,

R.

.

,

:

myfun<-function(S,F){data<-read.table(F)

plot(data$V1,data$V2,type=\"l\")title(S)}

,

.

,

.

,

,

.

,

source()

.

68

R

,,

.RData.fordetails).”).

,

‘.Rprofile’

,

‘Rprofile’(

(

?Startup“R

,

,

myfun(\"swallow\\"Swal.dat\").,

:

layout(matrix(1:3,3,1))myfun(\"swallow\\"Swal.dat\")myfun(\"wren\\"Wrenn.dat\")myfun(\"dunnock\\"Dunn.dat\")

sapply()

:

layout(matrix(1:3,3,1))

species<-c(\"swallow\\"wren\\"dunnock\")

file<-c(\"Swal.dat\",\"Wren.dat\\"Dunn.dat\")sapply(species,myfun,file)

R

,

.

R

.

,

>foo<-function()print(x)>x<-1>foo()[1]1

x

foo()

,

R

x

,

(

x

,

.

>x<-1

>foo2<-function(){x<-2;print(x)}>foo2()[1]2>x[1]1

69

,

:

,

).

x

,print()

“”foofoo2

x,

foo2

x.:

..

,

,

.

:

(

).

,

:

foo<-function(arg1,arg2,arg3){...}arg1,...,foo()

,:foo(x,y,z).,

,

foo(arg3=z,arg2=y,arg1=x).R

.:

foo<-function(arg1,arg2=5,arg3=FALSE){...}

foo(x),foo(x,5,FALSE)

foo(x,arg3=FALSE)

.

,

foo(x,arg3=TRUE)

.,

.,R

.

Ricker

:󰀃󰀁

Nt+1

=Ntexpr1−

Nt

󰀂󰀄K

,.rN0(

K1

)

;

.

(

).

Ricker

.

ricker<-function(nzero,r,K=1,time=100,from=0,to=time){

N<-numeric(time+1)N[1]<-nzero

for(iin1:time)N[i+1]<-N[i]*exp(r*(1-N[i]/K))Time<-0:time

plot(Time,N,type=\"l\xlim=c(from,to))}

:

>layout(matrix(1:3,3,1))

>ricker(0.1,1);title(\"r=1\")>ricker(0.1,2);title(\"r=2\")>ricker(0.1,3);title(\"r=3\")

70

:

,

,

7R

.

RHOME/doc/manual/

R

:

•R27

[R-intro.pdf],

•R

[R-admin.pdf],

•R/

[R-data.pdf],•R

[R-exts.pdf],•R

[R-lang.pdf].

(pdf,html,texi,...)

.

FAQ.

RHOME/doc/html/FAQ(

AskedQuestions).R-FAQ

CRAN

http://cran.r-project.org/doc/FAQ/R-FAQ.html

.CRAN

,

R

(

)

29.

.R

;,

:http://www.R-project.org/mail.html.

‘r-help’.

R

,

(

).

.,

,

:

1.(

);

2.R-FAQ;3.‘r-help’

,

4.

”31.

2728

:.google.

http://www.R-project.org/doc/bib/R-publications.html29

http://cran.r-project.org/other-docs.html30

31

http://cran.r-project.org/search.html

http://www.r-project.org/posting-guide.html

71

,

,Frequently

:

R

.28

R

‘r-help’

R

‘r-help’

30;

R

.

.:

RNews2001

,

32.

R.

R,

RDevelopmentCoreTeam(2005).R:Alanguageandenvi-ronmentforstatisticalcomputing.RFoundationforStatisti-calComputing,Vienna,Austria.ISBN3-900051-07-0,URL:

http://www.R-project.org.

32

http://cran.r-project.org/doc/Rnews/

72

因篇幅问题不能全部显示,请点此查看更多更全内容