c# free pdf viewer : Add document to pdf pages application software utility html windows .net visual studio R-intro2-part789

Chapter3:Objects,theirmodesandattributes
15
willprintitindataframeform,whichisratherlikeamatrix,whereas
> unclass(winter)
willprintitasanordinarylist.Onlyinratherspecialsituationsdoyouneedtousethisfacility,
butoneiswhenyouarelearningtocometotermswiththeideaofclassandgenericfunctions.
GenericfunctionsandclasseswillbediscussedfurtherinSection10.9[Objectorientation],
page48,butonlybriefly.
Add document to pdf pages - insert pages into PDF file in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
Guide C# Users to Insert (Empty) PDF Page or Pages from a Supported File Format
add multi page pdf to word document; add page to existing pdf file
Add document to pdf pages - VB.NET PDF Page Insert Library: insert pages into PDF file in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
Easy to Use VB.NET APIs to Add a New Blank Page to PDF Document
add page to pdf in preview; add remove pages from pdf
16
4 Orderedandunorderedfactors
Afactorisavectorobjectusedtospecifyadiscreteclassification(grouping)ofthecomponents
ofothervectorsofthesamelength.Rprovidesbothorderedandunordered factors. Whilethe
“real”applicationoffactorsiswithmodelformulae(seeSection11.1.1[Contrasts],page53),we
herelookataspecificexample.
4.1 Aspecificexample
Suppose,forexample,wehaveasampleof30taxaccountantsfromallthestatesandterritories
of Australia
1
and their individual l state e of origin n is s specified d by a character vector of state
mnemonicsas
> state e <- c("tas", "sa", , "qld", , "nsw", "nsw", "nt", , "wa", "wa",
"qld", "vic", , "nsw", , "vic", "qld", "qld", "sa", , "tas",
"sa", "nt", "wa", "vic", , "qld", "nsw", "nsw", "wa",
"sa", "act", , "nsw", , "vic", "vic", "act")
Noticethatinthecaseofacharactervector,“sorted”meanssortedinalphabeticalorder.
Afactorissimilarlycreatedusingthefactor()function:
> statef f <- factor(state)
Theprint()functionhandlesfactorsslightlydifferentlyfromotherobjects:
> statef
[1] tas s sa a qld d nsw w nsw w nt t wa wa qld d vic nsw w vic c qld d qld d sa
[16] tas s sa a nt wa vic c qld nsw nsw wa a sa a act t nsw w vic c vic c act
Levels: act t nsw w nt qld d sa tas s vic c wa
Tofindoutthelevelsofafactorthefunctionlevels()canbeused.
> levels(statef)
[1] "act" " "nsw" "nt" " "qld" " "sa" " "tas" " "vic" " "wa"
4.2 Thefunctiontapply()andraggedarrays
Tocontinuethepreviousexample,supposewehavetheincomesofthesametaxaccountantsin
anothervector(insuitablylargeunitsofmoney)
> incomes <- c(60, , 49, 40, , 61, , 64, , 60, , 59, , 54, , 62, 69, 70, 42, 56,
61, 61, 61, , 58, , 51, , 48, , 65, , 49, , 49, 41, 48, 52, 46,
59, 46, 58, , 43)
To calculate thesamplemean incomefor eachstatewecan now use thespecialfunction
tapply():
> incmeans s <- tapply(incomes, statef, , mean)
givingameansvectorwiththecomponentslabelledbythelevels
act
nsw
nt
qld
sa
tas
vic
wa
44.500 57.333 55.500 0 53.600 0 55.000 0 60.500 0 56.000 0 52.250
Thefunctiontapply()isusedtoapplyafunction,heremean(),toeachgroupofcomponents
ofthefirstargument,hereincomes,definedbythelevelsofthesecondcomponent,herestatef
2
,
1
Readersshould notethat there areeight states andterritories in Australia,namely theAustralian Capital
Territory, New SouthWales,theNorthern Territory, Queensland,SouthAustralia,Tasmania,Victoriaand
WesternAustralia.
2
Notethattapply()alsoworksinthiscasewhenitssecondargumentisnotafactor,e.g.,‘tapply(incomes,
state)’,andthisistrueforquiteafewotherfunctions,sinceargumentsarecoercedtofactorswhennecessary
(usingas.factor()).
C# PDF Page Extract Library: copy, paste, cut PDF pages in C#.net
pageIndexes.Add(3); // The 4th page. Create the new document with 3 String outputFilePath = Program.RootPath + "\\" Output.pdf"; newDoc.Save(outputFilePath
add page numbers to a pdf file; add page break to pdf
VB.NET PDF Page Extract Library: copy, paste, cut PDF pages in vb.
pageIndexes.Add(3) ' The 4th page Create the new document with 3 Dim outputFilePath As String = Program.RootPath + "\\" Output.pdf" newDoc.Save(outputFilePath
add and remove pages from pdf file online; add and remove pages from a pdf
Chapter4:Orderedandunorderedfactors
17
asiftheywereseparatevectorstructures. Theresult t isastructureofthesamelengthasthe
levelsattributeofthefactorcontainingtheresults.Thereadershouldconsultthehelpdocument
formoredetails.
Supposefurtherweneededtocalculatethestandarderrorsofthestateincomemeans.Todo
thisweneedtowriteanRfunctiontocalculatethestandarderrorforanygivenvector. Since
thereis anbuiltinfunctionvar()tocalculate the samplevariance, , sucha functionisavery
simpleoneliner,specifiedbytheassignment:
> stderr r <- function(x) ) sqrt(var(x)/length(x))
(WritingfunctionswillbeconsideredlaterinChapter10[Writingyourownfunctions],page42,
andinthiscasewasunnecessaryasRalsohasabuiltinfunctionsd().) Afterthisassignment,
thestandarderrorsarecalculatedby
> incster <- tapply(incomes, , statef, stderr)
andthevaluescalculatedarethen
> incster
act
nsw nt
qld
sa tas
vic
wa
1.5 4.3102 4.5 4.1061 2.7386 0.5 5.244 2.6575
As anexercise youmay y care e to find the usual 95% confidence limits s for the e state mean
incomes. To o dothis youcoulduse tapply() once morewiththe length() functiontofind
the sample sizes, and the qt() ) function to o find the percentage points of the appropriate e t-
distributions. (YoucouldalsoinvestigateR’sfacilitiesfort-tests.)
The functiontapply() canalsobe usedtohandle morecomplicatedindexingofa vector
bymultiplecategories. Forexample,wemightwishtosplitthetaxaccountantsbybothstate
andsex. Howeverinthissimpleinstance(justonefactor)whathappenscanbethoughtofas
follows. Thevaluesinthevectorarecollectedintogroupscorrespondingtothedistinctentries
inthefactor. Thefunctionisthenappliedtoeachofthesegroupsindividually. Thevalueisa
vectoroffunctionresults,labelledbythelevelsattributeofthefactor.
Thecombinationofavectorandalabellingfactorisanexampleofwhatissometimescalled
araggedarray,sincethesubclasssizesarepossibly irregular. . Whenthesubclass s sizes areall
thesametheindexingmaybedoneimplicitlyandmuchmoreefficiently,asweseeinthenext
section.
4.3 Orderedfactors
The levels of factors are stored inalphabetical order, or in the order they were specifiedto
factoriftheywerespecifiedexplicitly.
Sometimes the levels will have a a natural ordering that t we e want t to o record and want our
statisticalanalysistomakeuseof. Theordered() ) functioncreates such h orderedfactors s but
is otherwiseidenticaltofactor. . For r most purposes theonly differencebetweenorderedand
unorderedfactors is s that the former are printedshowing the orderingof the e levels, , but t the
contrastsgeneratedfortheminfittinglinearmodelsaredifferent.
VB.NET PDF Page Delete Library: remove PDF pages in vb.net, ASP.
Add necessary references: RasterEdge.Imaging.Basic.dll. This is a VB .NET example for how to delete a range of pages from a PDF document.
add and delete pages from pdf; adding page numbers to pdf documents
C# PDF Page Delete Library: remove PDF pages in C#.net, ASP.NET
options, including setting a single page, a series of pages, and random pages to be C#.NET Project DLLs for Deleting PDF Document Page. Add necessary references
add blank page to pdf preview; adding a page to a pdf file
18
5 Arraysandmatrices
5.1 Arrays
Anarray can n be considered as s a multiply subscriptedcollectionofdata entries,for example
numeric. R R allows simple e facilities s for creating g and handling g arrays, and d in n particular r the
specialcaseofmatrices.
Adimensionvectorisavectorofnon-negativeintegers. Ifitslengthisk k thenthearrayis
k-dimensional,e.g.amatrixisa2-dimensionalarray. Thedimensionsareindexedfromoneup
tothevaluesgiveninthedimensionvector.
AvectorcanbeusedbyRasanarrayonlyifithasadimensionvectorasitsdimattribute.
Suppose,forexample,zisavectorof1500elements. Theassignment
> dim(z) ) <- c(3,5,100)
givesitthedimattributethatallowsittobetreatedasa3by5by100array.
Other functionssuchasmatrix() andarray() areavailableforsimplerandmorenatural
lookingassignments,asweshallseeinSection5.4[Thearray()function],page20.
Thevaluesinthedatavectorgivethevaluesinthearrayinthesameorderastheywould
occurinFORTRAN,thatis“columnmajororder,”withthefirstsubscriptmovingfastestand
thelastsubscriptslowest.
Forexampleifthedimensionvectorforanarray,saya,isc(3,4,2)thenthereare34
2= 24entries ina andthe data vector holds theminthe order a[1,1,1],a[2,1,1],...,
a[2,4,2],a[3,4,2].
Arrayscanbeone-dimensional: sucharraysareusuallytreatedinthesamewayasvectors
(includingwhenprinting),buttheexceptionscancauseconfusion.
5.2 Arrayindexing. . Subsectionsofanarray
Individualelementsofanarraymaybereferencedbygivingthenameofthearrayfollowedby
thesubscriptsinsquarebrackets,separatedbycommas.
Moregenerally,subsectionsofanarraymaybespecifiedbygivingasequenceofindexvectors
inplaceofsubscripts;howeverifanyindexpositionisgivenanemptyindexvector,thenthefull
rangeofthatsubscriptistaken.
Continuingthepreviousexample,a[2,,]isa42arraywithdimensionvectorc(4,2)and
datavectorcontainingthevalues
c(a[2,1,1], a[2,2,1], a[2,3,1], , a[2,4,1],
a[2,1,2], a[2,2,2], a[2,3,2], , a[2,4,2])
inthatorder. a[,,]standsfortheentirearray,whichisthesameasomittingthesubscripts
entirelyandusingaalone.
Foranyarray,sayZ,thedimensionvectormaybereferencedexplicitlyasdim(Z)(oneither
sideofanassignment).
Also,ifanarraynameisgivenwithjustonesubscriptorindexvector,thenthecorresponding
valuesofthedatavectoronlyareused;inthiscasethedimensionvectorisignored.Thisisnot
thecase,however,ifthesingleindexisnotavectorbutitselfanarray,aswenextdiscuss.
VB.NET PDF insert image library: insert images into PDF in vb.net
VB.NET PDF - Add Image to PDF Page in VB.NET. Guide VB.NET Programmers How to Add Images in PDF Document Using XDoc.PDF SDK for VB.NET.
add page number pdf; add a page to a pdf file
C# PDF Password Library: add, remove, edit PDF file password in C#
in C#.NET framework. Support to add password to PDF document online or in C#.NET WinForms for PDF file protection. Able to create a
add page pdf; add a page to a pdf online
Chapter5:Arraysandmatrices
19
5.3 Indexmatrices
Aswellasanindexvectorinanysubscriptposition,amatrixmaybeusedwithasingleindex
matrix inordereithertoassignavectorofquantitiestoanirregular r collectionofelementsin
thearray,ortoextractanirregularcollectionasavector.
Amatrixexamplemakestheprocessclear. Inthecaseofadoublyindexedarray,anindex
matrixmaybegivenconsistingoftwocolumnsandasmanyrowsasdesired. Theentriesinthe
indexmatrixaretherowandcolumnindicesforthedoublyindexedarray.Supposeforexample
wehavea4by5arrayXandwewishtodothefollowing:
 ExtractelementsX[1,3],X[2,2]andX[3,1]asavectorstructure,and
 ReplacetheseentriesinthearrayXbyzeroes.
Inthiscaseweneeda3by2subscriptarray,asinthefollowingexample.
> x x <- array(1:20, dim=c(4,5))
# Generatea4by5array.
> x
[,1] [,2] ] [,3] [,4] [,5]
[1,]
1
5
9
13
17
[2,]
2
6
10
14
18
[3,]
3
7
11
15
19
[4,]
4
8
12
16
20
> i i <- array(c(1:3,3:1), dim=c(3,2))
> i
# iisa3by2indexarray.
[,1] [,2]
[1,]
1
3
[2,]
2
2
[3,]
3
1
> x[i]
# Extractthoseelements
[1] 9 6 3
> x[i] ] <- - 0
# Replacethoseelementsbyzeros.
> x
[,1] [,2] ] [,3] [,4] [,5]
[1,]
1
5
0
13
17
[2,]
2
0
10
14
18
[3,]
0
7
11
15
19
[4,]
4
8
12
16
20
>
Negativeindicesarenotallowedinindexmatrices. NAandzerovaluesareallowed: rowsinthe
indexmatrix containinga zero areignored,androwscontaininganNAproduce anNAinthe
result.
Asaless trivialexample,supposewewishtogeneratean(unreduced) designmatrixfora
block designdefinedby factors blocks(b levels)andvarieties (v levels). . Further r suppose
therearenplotsintheexperiment. Wecouldproceedasfollows:
> Xb <- - matrix(0, n, , b)
> Xv <- - matrix(0, n, , v)
> ib <- - cbind(1:n, blocks)
> iv <- - cbind(1:n, varieties)
> Xb[ib] ] <- 1
> Xv[iv] ] <- 1
> X X <- cbind(Xb, Xv)
Toconstructtheincidencematrix,Nsay,wecoulduse
> N N <- crossprod(Xb, , Xv)
C# PDF insert image Library: insert images into PDF in C#.net, ASP
Create high resolution PDF file without image quality losing in ASP.NET application. Add multiple images to multipage PDF document in .NET WinForms.
adding page numbers to a pdf file; adding page numbers in pdf
C# PDF File & Page Process Library SDK for C#.net, ASP.NET, MVC
Document Protect. Password: Set File Permissions. Password: Open Document. Edit Digital Highlight Text. Add Text. Add Text Box. Drawing Markups. PDF Print. Work
add page number to pdf print; add pages to pdf
Chapter5:Arraysandmatrices
20
Howeverasimplerdirectwayofproducingthismatrixistousetable():
> N N <- table(blocks, , varieties)
Index matrices must be numerical: : any y other form m of f matrix (e.g. . a logical or character
matrix)suppliedasamatrixistreatedasanindexingvector.
5.4 Thearray()function
Aswellasgivingavectorstructureadimattribute,arrayscanbeconstructedfromvectorsby
thearrayfunction,whichhastheform
> Z Z <- array(data_vector, dim_vector)
Forexample,ifthevectorhcontains24orfewer,numbersthenthecommand
> Z Z <- array(h, , dim=c(3,4,2))
wouldusehtosetup3by4by2arrayinZ.Ifthesizeofhisexactly24theresultisthesame
as
> Z Z <- h ; dim(Z) <- - c(3,4,2)
Howeverifhisshorterthan24,itsvaluesarerecycledfromthebeginningagaintomakeit
uptosize24(seeSection5.4.1[Therecyclingrule],page20)but dim(h)<-c(3,4,2)would
signalanerroraboutmismatchinglength. Asanextremebutcommonexample
> Z Z <- array(0, , c(3,4,2))
makesZanarrayofallzeros.
Atthispointdim(Z)standsforthedimensionvectorc(3,4,2),andZ[1:24]standsforthe
datavectorasitwasinh,andZ[]withanemptysubscriptorZwithnosubscriptstandsfor
theentirearrayasanarray.
Arraysmaybeusedinarithmeticexpressionsandtheresultisanarrayformedbyelement-
by-elementoperationsonthedatavector.Thedimattributesofoperandsgenerallyneedtobe
thesame,andthisbecomesthedimensionvectoroftheresult. SoifA,BandCareallsimilar
arrays,then
> D D <- 2*A*B B + + C + 1
makes Dasimilar arraywithits datavectorbeingtheresultofthe givenelement-by-element
operations. Howeverthepreciseruleconcerningmixedarrayandvectorcalculationshastobe
consideredalittlemorecarefully.
5.4.1 Mixedvectorandarrayarithmetic. . Therecyclingrule
The precise rule affecting element by y element t mixed d calculations s with h vectors and arrays s is
somewhatquirkyandhardtofindinthereferences.Fromexperiencewehavefoundthefollowing
tobeareliableguide.
 Theexpressionisscannedfromlefttoright.
 Anyshortvectoroperandsareextendedbyrecyclingtheirvaluesuntiltheymatchthesize
ofanyotheroperands.
 Aslongasshortvectorsandarraysonlyareencountered,thearraysmustallhavethesame
dimattributeoranerrorresults.
 Anyvectoroperandlongerthanamatrixorarrayoperandgeneratesanerror.
 Ifarraystructuresarepresentandnoerrororcoerciontovectorhasbeenprecipitated,the
resultisanarraystructurewiththecommondimattributeofitsarrayoperands.
Chapter5:Arraysandmatrices
21
5.5 Theouterproductoftwoarrays
An important t operation n on arrays s is the outer r product. . If f a andb are two numeric arrays,
theirouterproductisanarraywhosedimensionvectorisobtainedbyconcatenatingtheirtwo
dimensionvectors (order isimportant),andwhose datavector is gotby formingallpossible
productsofelementsofthedatavectorofawiththoseofb. Theouterproductis s formedby
thespecialoperator%o%:
> ab <- - a a %o% % b
Analternativeis
> ab <- - outer(a, b, "*")
Themultiplicationfunctioncanbereplacedby anarbitraryfunctionoftwovariables. . For
exampleifwewishedtoevaluatethefunctionf(x;y)=cos(y)=(1+x
2
)over aregulargridof
valueswithx-andy-coordinatesdefinedbytheRvectorsxandyrespectively,wecouldproceed
asfollows:
> f f <- function(x, y) cos(y)/(1 1 + + x^2)
> z z <- outer(x, , y, , f)
Inparticulartheouterproductoftwoordinaryvectors isadoublysubscriptedarray(that
is a a matrix, of f rank at most t 1). . Notice e that t the e outer r product operator is of f course e non-
commutative.DefiningyourownRfunctionswillbeconsideredfurtherinChapter10[Writing
yourownfunctions],page42.
Anexample: Determinantsof2by2single-digitmatrices
Asanartificialbutcuteexample,considerthedeterminantsof2by2matrices[a;b;c;d]where
eachentryisanon-negativeintegerintherange0;1;:::;9,thatisadigit.
The problemistofindthedeterminants,ad bc,ofallpossiblematrices s ofthisformand
representthefrequencywithwhicheachvalueoccurs asahigh density y plot. . This s amountsto
findingtheprobabilitydistributionofthedeterminantifeachdigitischosenindependentlyand
uniformlyatrandom.
Aneatwayofdoingthisusestheouter()functiontwice:
> d d <- outer(0:9, 0:9)
> fr <- - table(outer(d, d, "-"))
> plot(as.numeric(names(fr)), , fr, type="h",
xlab="Determinant", ylab="Frequency")
Notice the coercion of the names s attribute e of the frequency table to numeric in order to
recovertherangeofthedeterminantvalues.The“obvious”wayofdoingthisproblemwithfor
loops,tobediscussedinChapter9[Loopsandconditionalexecution],page40,issoinefficient
astobeimpractical.
Itisalsoperhapssurprisingthatabout1in20suchmatricesissingular.
5.6 Generalizedtransposeofanarray
Thefunctionaperm(a,perm)maybeusedtopermuteanarray,a. Theargumentpermmustbe
apermutationoftheintegersf1;:::;kg,wherekisthenumberofsubscriptsina.Theresultof
thefunctionisanarrayofthesamesizeasabutwitholddimensiongivenbyperm[j]becoming
thenew j-thdimension. . Theeasiest t wayto think of this operationis as ageneralization n of
transpositionformatrices.IndeedifAisamatrix,(thatis,adoublysubscriptedarray)thenB
givenby
> B B <- aperm(A, , c(2,1))
isjustthetransposeofA. Forthisspecialcaseasimplerfunctiont()isavailable,sowecould
haveusedB<-t(A).
Chapter5:Arraysandmatrices
22
5.7 Matrixfacilities
Asnotedabove,amatrixisjustanarraywithtwosubscripts.Howeveritissuchanimportant
specialcaseit needsaseparatediscussion. . R R containsmanyoperatorsandfunctions thatare
availableonlyformatrices. Forexamplet(X)isthematrixtransposefunction,asnotedabove.
The functions nrow(A) andncol(A) ) give e the number r of f rows s and columns s in n the matrix A
respectively.
5.7.1 Matrixmultiplication
Theoperator%*%isusedformatrixmultiplication. Annby1or1bynmatrixmayofcourse
beusedasann-vectorifinthecontextsuchisappropriate. Conversely,vectorswhichoccurin
matrixmultiplicationexpressionsareautomaticallypromotedeithertoroworcolumnvectors,
whicheverismultiplicativelycoherent,ifpossible,(althoughthisisnot always unambiguously
possible,asweseelater).
If,forexample,AandBaresquarematricesofthesamesize,then
> A A * B
isthematrixofelementbyelementproductsand
> A A %*% B
isthematrixproduct.Ifxisavector,then
> x x %*% A A %*% % x
isaquadraticform.
1
The function n crossprod() ) forms s “crossproducts”, , meaning g that crossprod(X,y) is s the
sameast(X)%*%ybuttheoperationismoreefficient.Ifthesecondargumenttocrossprod()
isomitteditistakentobethesameasthefirst.
The meaning of diag() depends onits argument. . diag(v), , where v v is a vector, , gives s a
diagonalmatrixwithelementsofthevectorasthediagonalentries.Ontheotherhanddiag(M),
whereMisamatrix,givesthevectorofmaindiagonalentriesofM. Thisisthesameconvention
asthatusedfordiag()inMatlab.Also,somewhatconfusingly,ifkisasinglenumericvalue
thendiag(k)isthekbykidentitymatrix!
5.7.2 Linearequationsandinversion
Solvinglinearequationsistheinverseofmatrixmultiplication.Whenafter
> b b <- A %*% % x
onlyAandbaregiven,thevectorxisthesolutionofthatlinearequationsystem. InR,
> solve(A,b)
solvesthesystem,returningx(uptosomeaccuracyloss). Notethatinlinearalgebra,formally
x=A
1
bwhereA
1
denotestheinverse ofA,whichcanbecomputedby
solve(A)
butrarelyis needed. . Numerically,itisbothinefficientandpotentiallyunstabletocomputex
<-solve(A)%*%binsteadofsolve(A,b).
Thequadraticformx
T
A
1
xwhichisusedinmultivariatecomputations,shouldbecomputed
bysomethinglike
2
x%*%solve(A,x),ratherthancomputingtheinverseofA.
1
Notethat x%*%xis ambiguous, asitcould meaneither x
T
xor xx
T
,wherexisthecolumn form. . In n such
casesthesmaller matrixseems implicitlytobetheinterpretation adopted,sothescalar x
T
xisinthis case
theresult. Thematrixxx
T
maybecalculatedeitherbycbind(x)%*%xorx%*%rbind(x)sincetheresultof
rbind()orcbind()isalwaysamatrix. However,thebestwaytocomputex
T
xorxx
T
iscrossprod(x)orx
%o%xrespectively.
2
Even better would be toform m amatrix square root t B with A= BB
T
and find the squared length of the
solutionofBy=x,perhapsusingtheCholeskyoreigendecompositionofA.
Chapter5:Arraysandmatrices
23
5.7.3 Eigenvaluesandeigenvectors
The function n eigen(Sm) ) calculates the eigenvalues and d eigenvectors s of f a a symmetric matrix
Sm. Theresultofthis s functionisalistoftwocomponents named d valuesandvectors. . The
assignment
> ev <- - eigen(Sm)
willassignthislist to ev. . Thenev$valis s thevector of eigenvalues of Smandev$vec is the
matrixofcorrespondingeigenvectors. Hadweonlyneededtheeigenvalueswecouldhaveused
theassignment:
> evals s <- eigen(Sm)$values
evals now w holds the vector of eigenvalues s and d the e second d component is discarded. . If f the
expression
> eigen(Sm)
is usedbyitselfasacommandthe twocomponentsareprinted,withtheirnames. . Forlarge
matricesit isbetter toavoidcomputingthe eigenvectors iftheyarenotneededby usingthe
expression
> evals s <- eigen(Sm, , only.values s = = TRUE)$values
5.7.4 Singularvaluedecompositionanddeterminants
Thefunctionsvd(M)takesanarbitrarymatrixargument,M,andcalculatesthesingularvalue
decompositionofM. ThisconsistsofamatrixoforthonormalcolumnsUwiththesamecolumn
spaceas M, , asecondmatrix x of orthonormalcolumns s Vwhose e columnspace is therow space
ofMandadiagonalmatrixofpositiveentriesDsuchthatM=U%*%D%*%t(V). Disactually
returnedasavector ofthediagonalelements. . Theresult t ofsvd(M) isactuallyalistofthree
componentsnamedd,uandv,withevidentmeanings.
IfMisinfactsquare,then,itisnothardtoseethat
> absdetM <- prod(svd(M)$d)
calculatestheabsolutevalueofthedeterminantofM. Ifthiscalculationwereneededoftenwith
avarietyofmatricesitcouldbedefinedasanRfunction
> absdet t <- function(M) ) prod(svd(M)$d)
afterwhichwecoulduseabsdet()asjustanotherRfunction.Asafurthertrivialbutpotentially
usefulexample,youmightliketoconsiderwritingafunction,say tr(),tocalculatethetrace
ofasquarematrix. [Hint: Youwillnotneedtouseanexplicitloop. Lookagainatthediag()
function.]
R has a builtinfunctiondetto calculate adeterminant, , includingthesign,andanother,
determinant,togivethesignandmodulus(optionallyonlogscale),
5.7.5 LeastsquaresfittingandtheQRdecomposition
The function lsfit() returns s a a list giving g results of f a a least squares s fitting procedure. . An
assignmentsuchas
> ans s <- lsfit(X, y)
givestheresultsofaleastsquaresfitwhereyisthevectorofobservationsandXisthedesign
matrix. Seethehelpfacilityformoredetails,andalsoforthefollow-upfunctionls.diag()for,
amongotherthings,regressiondiagnostics. Notethatagrandmeantermisautomaticallyin-
cludedandneednotbeincludedexplicitlyasacolumnofX.Furthernotethatyoualmostalways
willprefer using lm(.) (see Section n 11.2[Linear r models], , page 54)tolsfit() ) for regression
modelling.
Anothercloselyrelatedfunctionisqr()anditsallies. Considerthefollowingassignments
> Xplus s <- qr(X)
Chapter5:Arraysandmatrices
24
> b b <- qr.coef(Xplus, y)
> fit t <- qr.fitted(Xplus, y)
> res s <- qr.resid(Xplus, y)
Thesecomputetheorthogonalprojectionofy ontotherangeofXinfit,theprojectiononto
theorthogonalcomplementinresandthecoefficientvectorfortheprojectioninb,thatis,bis
essentiallytheresultoftheMatlab‘backslash’operator.
ItisnotassumedthatXhasfullcolumnrank. Redundancieswillbediscoveredandremoved
astheyarefound.
Thisalternativeistheolder,low-levelwaytoperformleastsquarescalculations. Although
stillusefulinsomecontexts,itwouldnowgenerallybereplacedbythestatisticalmodelsfeatures,
aswillbediscussedinChapter11[StatisticalmodelsinR],page51.
5.8 Formingpartitionedmatrices,cbind() ) andrbind()
Aswehavealreadyseeninformally,matricescanbebuiltupfromothervectorsandmatrices
bythefunctionscbind()andrbind(). Roughlycbind()formsmatricesbybindingtogether
matriceshorizontally,orcolumn-wise,andrbind()vertically,orrow-wise.
Intheassignment
> X X <- cbind(arg_1, arg_2, , arg_3, , ...)
the arguments to cbind() must be either r vectors s of any y length, or r matrices with h the same
columnsize,thatis thesame number ofrows. . Theresultisamatrix x withtheconcatenated
argumentsarg
1,arg
2,... formingthecolumns.
Ifsomeoftheargumentstocbind()arevectorstheymaybeshorterthanthecolumnsize
ofanymatricespresent,inwhichcasetheyarecyclicallyextendedtomatchthematrixcolumn
size(orthelengthofthelongestvectorifnomatricesaregiven).
The functionrbind() does the corresponding operationfor rows. . Inthis s case any vector
argument,possiblycyclicallyextended,areofcoursetakenasrowvectors.
SupposeX1 and d X2 2 have the same number of rows. . Tocombine e these by columns intoa
matrixX,togetherwithaninitialcolumnof1swecanuse
> X X <- cbind(1, , X1, , X2)
Theresultofrbind()orcbind()alwayshasmatrixstatus.Hencecbind(x)andrbind(x)
arepossiblythesimplestwaysexplicitlytoallowthevectorxtobetreatedasacolumnorrow
matrixrespectively.
5.9 Theconcatenationfunction,c(),witharrays
Itshouldbenotedthatwhereascbind()andrbind()areconcatenationfunctionsthatrespect
dimattributes,thebasicc()functiondoesnot,butratherclearsnumericobjectsofalldimand
dimnamesattributes. Thisisoccasionallyusefulinitsownright.
Theofficialwaytocoerceanarraybacktoasimplevectorobjectistouseas.vector()
> vec c <- as.vector(X)
Howeverasimilarresultcanbeachievedby usingc() withjustone argument,simplyfor
thisside-effect:
> vec c <- c(X)
There are slight t differences between the two, , but t ultimately the choice e between them is
largelyamatterofstyle(withtheformerbeingpreferable).
Documents you may be interested
Documents you may be interested