c# free pdf viewer : Adding a page to a pdf control Library system azure asp.net .net console R-intro1-part788

Chapter1:Introductionandpreliminaries
5
Commandsareseparatedeitherbyasemi-colon(‘;’),orbyanewline.Elementarycommands
canbegroupedtogetherintoonecompoundexpressionbybraces(‘{’and‘}’).Commentscan
beputalmost
2
anywhere,startingwithahashmark(‘#’),everythingtotheendofthelineisa
comment.
Ifacommandisnotcompleteattheendofaline,Rwillgiveadifferentprompt,bydefault
+
onsecondandsubsequentlinesandcontinuetoreadinputuntilthecommandissyntactically
complete. This s promptmaybechangedbytheuser. . Wewillgenerallyomitthecontinuation
promptandindicatecontinuationbysimpleindenting.
Commandlinesenteredattheconsolearelimited
3
toabout4095bytes(notcharacters).
1.9 Recallandcorrectionofpreviouscommands
UndermanyversionsofUNIXandonWindows,Rprovidesamechanismforrecallingandre-
executingpreviouscommands. Theverticalarrowkeysonthekeyboardcanbeusedtoscroll
forwardandbackwardthroughacommandhistory.Onceacommandislocatedinthisway,the
cursorcanbemovedwithinthecommandusingthehorizontalarrowkeys,andcharacterscan
beremovedwiththeDELkeyoraddedwiththeotherkeys.Moredetailsareprovidedlater: see
AppendixC[Thecommand-lineeditor],page92.
The recallandeditingcapabilitiesunderUNIXarehighly customizable. . Youcanfindout
howtodothisbyreadingthemanualentryforthereadlinelibrary.
Alternatively,the Emacs text editor provides moregeneralsupport mechanisms (via
ESS
,
EmacsSpeaksStatistics)forworkinginteractivelywithR.SeeSection“RandEmacs”inThe
RstatisticalsystemFAQ.
1.10 Executingcommandsfromordivertingoutputtoafile
Ifcommands
4
arestoredinanexternalfile,saycommands.Rintheworkingdirectorywork,they
maybeexecutedatanytimeinanRsessionwiththecommand
> source("commands.R")
ForWindowsSourceisalsoavailableontheFilemenu.Thefunctionsink,
> sink("record.lis")
willdivertallsubsequentoutputfromtheconsoletoanexternalfile,record.lis.Thecommand
> sink()
restoresittotheconsoleonceagain.
1.11 Datapermanencyandremovingobjects
TheentitiesthatRcreatesandmanipulatesareknownasobjects.Thesemaybevariables,arrays
ofnumbers,characterstrings,functions,ormoregeneralstructuresbuiltfromsuchcomponents.
DuringanRsession,objectsarecreatedandstoredbyname(wediscussthisprocessinthe
nextsession). TheRcommand
> objects()
(alternatively,ls())canbeusedtodisplaythenamesof(mostof)theobjectswhicharecurrently
storedwithinR.Thecollectionofobjectscurrentlystorediscalledtheworkspace.
2
notinsidestrings,norwithintheargumentlistofafunctiondefinition
3
someoftheconsoleswillnotallowyoutoentermore,andamongstthosewhichdosomewillsilentlydiscard
theexcessandsomewilluseitasthestartofthenextline.
4
ofunlimitedlength.
Adding a page to a pdf - 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
adding page numbers to pdf files; add page number pdf file
Adding a page to a pdf - 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 number to pdf preview; add a page to a pdf
6
Toremoveobjectsthefunctionrmisavailable:
> rm(x, , y, z, ink, junk, temp, foo, bar)
AllobjectscreatedduringanRsessioncanbestoredpermanentlyinafileforuseinfuture
Rsessions. AttheendofeachRsessionyouaregiventheopportunitytosaveallthecurrently
availableobjects.Ifyouindicatethatyouwanttodothis,theobjectsarewrittentoafilecalled
.RData
5
inthecurrentdirectory,andthecommandlinesusedinthesessionaresavedtoafile
called.Rhistory.
WhenRisstartedatlatertimefromthesamedirectoryitreloadstheworkspacefromthis
file.Atthesametimetheassociatedcommandshistoryisreloaded.
Itisrecommendedthatyoushoulduseseparateworkingdirectoriesforanalysesconducted
withR.Itisquitecommonforobjects withnames xandytobecreatedduringananalysis.
Names like this areoften n meaningful inthe context t of asingleanalysis, , but t it canbequite
hardtodecidewhattheymightbewhentheseveralanalyseshavebeenconductedinthesame
directory.
5
Theleading“dot”inthisfilenamemakesitinvisibleinnormalfilelistingsinUNIX,andindefaultGUIfile
listingsonOSXandWindows.
VB.NET PDF File & Page Process Library SDK for vb.net, ASP.NET
page modifying page, you will find detailed guidance on creating, loading, merge and splitting PDF pages and Files, adding a page into PDF document, deleting
adding page to pdf; add document to pdf pages
VB.NET PDF Library SDK to view, edit, convert, process PDF file
Perform annotation capabilities to mark, draw, and visualize objects on PDF document page. Capable of adding PDF file navigation features to your VB.NET program
adding a page to a pdf document; add page to pdf reader
7
2 Simplemanipulations;numbersandvectors
2.1 Vectorsandassignment
Roperatesonnameddatastructures.Thesimplestsuchstructureisthenumericvector,which
isasingleentity consistingofanorderedcollectionofnumbers. . Tosetupavectornamedx,
say,consistingoffivenumbers,namely10.4,5.6,3.1,6.4and21.7,usetheRcommand
> x x <- c(10.4, 5.6, 3.1, 6.4, 21.7)
Thisisanassignment statementusingthe e function c()whichinthiscontextcantakean
arbitrary number r of vector r arguments s andwhose e value e is s a vector got by concatenating its
argumentsendtoend.
1
Anumberoccurringbyitselfinanexpressionistakenasavectoroflengthone.
Notice that the assignment operator (‘<-’),whichconsists ofthe twocharacters ‘<’(“less
than”) and‘-’(“minus”)occurringstrictly side-by-sideandit‘points’totheobjectreceiving
thevalueoftheexpression. Inmostcontextsthe‘=’operatorcanbeusedasanalternative.
Assignmentcanalsobemade usingthe functionassign(). . Anequivalentway y ofmaking
thesameassignmentasaboveiswith:
> assign("x", , c(10.4, 5.6, , 3.1, 6.4, , 21.7))
Theusualoperator,<-,canbethoughtofasasyntacticshort-cuttothis.
Assignmentscanalsobemadeintheotherdirection,usingtheobviouschangeintheassign-
mentoperator.Sothesameassignmentcouldbemadeusing
> c(10.4, 5.6, , 3.1, 6.4, 21.7) -> x
Ifanexpressionisusedasacompletecommand,thevalueisprintedandlost
2
.Sonowifwe
weretousethecommand
> 1/x
thereciprocalsofthefivevalueswouldbeprintedattheterminal(andthevalueofx,ofcourse,
unchanged).
Thefurtherassignment
> y y <- c(x, 0, x)
wouldcreateavectorywith11entriesconsistingoftwocopiesofxwithazerointhemiddle
place.
2.2 Vectorarithmetic
Vectorscanbeusedinarithmeticexpressions,inwhichcasetheoperationsareperformedelement
byelement. Vectors s occurringinthe sameexpressionneednotallbe ofthesamelength. . If
theyarenot,thevalueoftheexpressionisavectorwiththesamelengthasthelongestvector
whichoccursintheexpression.Shortervectorsintheexpressionarerecycledasoftenasneedbe
(perhapsfractionally)untiltheymatchthelengthofthelongestvector.Inparticularaconstant
issimplyrepeated.Sowiththeaboveassignmentsthecommand
> v v <- 2*x + + y y + 1
generatesanewvectorvoflength11constructedbyaddingtogether,elementbyelement,2*x
repeated2.2times,yrepeatedjustonce,and1repeated11times.
1
Withotherthanvectortypesofargument,suchaslistmodearguments,theactionofc()isratherdifferent.
SeeSection6.2.1[Concatenatinglists],page27.
2
Actually,itisstillavailableas.Last.valuebeforeanyotherstatementsareexecuted.
C# PDF insert image Library: insert images into PDF in C#.net, ASP
image adding library control for PDF document, you can easily and quickly add an image, picture or logo to any position of specified PDF document file page.
add pages to pdf file; add pages to pdf without acrobat
C# PDF File & Page Process Library SDK for C#.net, ASP.NET, MVC
Provides you with examples for adding an (empty) page to a PDF and adding empty pages to a PDF from a supported file format, with customized options.
adding page numbers in pdf file; add pages to pdf document
Chapter2:Simplemanipulations;numbersandvectors
8
Theelementaryarithmeticoperatorsaretheusual+,-,*,/and^forraisingtoapower.In
additionallofthecommonarithmeticfunctions areavailable. . log,exp,sin,cos,tan,sqrt,
andsoon,allhavetheirusualmeaning.maxandminselectthelargestandsmallestelementsofa
vectorrespectively.rangeisafunctionwhosevalueisavectoroflengthtwo,namelyc(min(x),
max(x)). length(x)isthenumberofelementsinx,sum(x)givesthetotaloftheelementsin
x,andprod(x)theirproduct.
Twostatisticalfunctionsaremean(x)whichcalculatesthesamplemean,whichisthesame
assum(x)/length(x),andvar(x)whichgives
sum((x-mean(x))^2)/(length(x)-1)
orsamplevariance. Iftheargumenttovar()isann-by-pmatrixthevalueisap-by-psample
covariancematrixgotbyregardingtherowsasindependentp-variatesamplevectors.
sort(x)returnsavectorofthesamesizeasxwiththeelementsarrangedinincreasingorder;
howeverthereareothermoreflexiblesortingfacilitiesavailable(seeorder()or sort.list()
whichproduceapermutationtodothesorting).
Notethatmaxandminselectthelargestandsmallestvaluesintheirarguments,evenifthey
aregivenseveralvectors. Theparallel l maximumandminimumfunctionspmaxandpminreturn
avector(oflengthequaltotheir longestargument)that containsineachelementthelargest
(smallest)elementinthatpositioninanyoftheinputvectors.
For most purposes the e user r will not t be concerned d if f the “numbers” ” in a numeric vector
are integers,reals or evencomplex. . Internally y calculationsare doneasdouble precision n real
numbers,ordoubleprecisioncomplexnumbersiftheinputdataarecomplex.
Toworkwithcomplexnumbers,supplyanexplicitcomplexpart. Thus
sqrt(-17)
willgiveNaNandawarning,but
sqrt(-17+0i)
willdothecomputationsascomplexnumbers.
2.3 Generatingregularsequences
Rhasanumberoffacilitiesforgeneratingcommonlyusedsequencesofnumbers. Forexample
1:30is thevectorc(1,2,...,29,30). . Thecolonoperatorhashighprioritywithinanex-
pression,so,forexample2*1:15isthevectorc(2,4,...,28,30).Putn<-10andcompare
thesequences1:n-1and1:(n-1).
Theconstruction30:1maybeusedtogenerateasequencebackwards.
Thefunctionseq()isamoregeneralfacilityforgeneratingsequences.Ithasfivearguments,
onlysomeofwhichmaybespecifiedinanyonecall. Thefirsttwoarguments,ifgiven,specify
thebeginningandendofthesequence,andifthesearetheonlytwoargumentsgiventheresult
isthesameasthecolonoperator.Thatisseq(2,10)isthesamevectoras2:10.
Argumentstoseq(),andtomanyotherRfunctions,canalsobegiveninnamedform,in
whichcasetheorderinwhichtheyappearisirrelevant.Thefirsttwoargumentsmaybenamed
from=value and d to=value; thus s seq(1,30), , seq(from=1,to=30) ) and d seq(to=30,from=1)
are all the same as 1:30. . The e next two arguments to seq() may y be e named by=value and
length=value,whichspecifyastepsizeandalengthforthesequencerespectively. Ifneither
oftheseisgiven,thedefaultby=1isassumed.
Forexample
> seq(-5, 5, by=.2) ) -> s3
generatesins3thevectorc(-5.0,-4.8,-4.6,...,4.6,4.8,5.0).Similarly
> s4 <- - seq(length=51, from=-5, , by=.2)
C# PDF insert text Library: insert text into PDF content in C#.net
C#.NET PDF SDK - Insert Text to PDF Document in C#.NET. Providing C# Demo Code for Adding and Inserting Text to PDF File Page with .NET PDF Library.
add page numbers to a pdf; adding page numbers to a pdf document
VB.NET PDF insert text library: insert text into PDF content in vb
VB.NET PDF - Insert Text to PDF Document in VB.NET. Providing Demo Code for Adding and Inserting Text to PDF File Page in VB.NET Program.
add blank page to pdf; add page to a pdf
Chapter2:Simplemanipulations;numbersandvectors
9
generatesthesamevectorins4.
Thefifthargumentmaybenamedalong=vector,whichisnormallyusedastheonlyargu-
menttocreatethesequence1,2,...,length(vector),ortheemptysequenceifthevector
isempty(asitcanbe).
Arelatedfunctionisrep()whichcanbeusedforreplicatinganobjectinvariouscomplicated
ways. Thesimplestformis
> s5 <- - rep(x, times=5)
whichwillputfivecopiesofxend-to-endins5. Anotherusefulversionis
> s6 <- - rep(x, each=5)
whichrepeatseachelementofxfivetimesbeforemovingontothenext.
2.4 Logicalvectors
As wellas numericalvectors,R allows manipulationoflogicalquantities. . Theelements s of a
logicalvector canhavethevalues TRUE, , FALSE,andNA A (for “not available”,see below). . The
first twoareoftenabbreviatedas T and d F, respectively. . Notehoweverthat t T and d Fare just
variableswhicharesettoTRUEandFALSEbydefault,butarenotreservedwordsandhencecan
beoverwrittenbytheuser. Hence,youshouldalwaysuseTRUEandFALSE.
Logicalvectorsaregeneratedbyconditions.Forexample
> temp p <- - x x > 13
setstempasavectorofthesamelengthasxwithvaluesFALSEcorrespondingtoelementsofx
wheretheconditionisnot metandTRUEwhereitis.
Thelogicaloperatorsare<,<=,>,>=,==forexactequalityand!=forinequality. Inaddition
ifc1andc2arelogicalexpressions,thenc1&c2istheirintersection(“and”),c1|c2istheir
union(“or”),and!c1isthenegationofc1.
Logical vectors may y be used d in ordinary arithmetic, , in n which case they are e coerced d into
numericvectors,FALSEbecoming0andTRUEbecoming1. Howevertherearesituationswhere
logicalvectorsandtheircoercednumericcounterpartsarenotequivalent,forexampleseethe
nextsubsection.
2.5 Missingvalues
Insomecases thecomponents of avector may not becompletely known. . Whenanelement
orvalueis“notavailable”ora“missingvalue”inthestatisticalsense,aplacewithinavector
maybereservedforitbyassigningitthespecialvalueNA. IngeneralanyoperationonanNA
becomesanNA. Themotivationforthisruleissimplythatifthespecificationofanoperation
isincomplete,theresultcannotbeknownandhenceisnotavailable.
The functionis.na(x) givesalogicalvectorof the samesizeas xwithvalue TRUEifand
onlyifthecorrespondingelementinxisNA.
> z z <- c(1:3,NA); ; ind d <- is.na(z)
Notice thatthelogicalexpressionx==NAis quite different fromis.na(x)sinceNAis not
reallyavaluebutamarkerforaquantitythatisnotavailable. Thusx==NAisavectorofthe
same lengthas x all l of f whose values areNA as the logicalexpressionitself isincompleteand
henceundecidable.
Notethatthereisasecondkindof“missing”valueswhichareproducedbynumericalcom-
putation,theso-calledNotaNumber,NaN,values. Examplesare
> 0/0
or
> Inf f - Inf
C# PDF Annotate Library: Draw, edit PDF annotation, markups in C#.
text comments on PDF page using C# demo code in Visual Stuodio .NET class. C#.NET: Add Text Box to PDF Document. Provide users with examples for adding text box
add page numbers to pdf document in preview; add page numbers to pdf files
VB.NET TIFF: Add New Image to TIFF File in Visual Basic .NET
However, RasterEdge VB.NET TIFF document processing SDK can offer you the reliable and extensive TIFF page image adding tool that allows you to directly insert
add pdf pages to word; adding page numbers pdf file
Chapter2:Simplemanipulations;numbersandvectors
10
whichbothgiveNaNsincetheresultcannotbedefinedsensibly.
In summary, , is.na(xx) ) is s TRUE both h for r NA and d NaN values. . To o differentiate these,
is.nan(xx)isonlyTRUEforNaNs.
Missingvalues aresometimes printed d as s <NA> whencharactervectors areprintedwithout
quotes.
2.6 Charactervectors
CharacterquantitiesandcharactervectorsareusedfrequentlyinR,forexampleasplotlabels.
Where needed they y are e denoted by a sequence of characters delimited by the double quote
character,e.g.,"x-values","Newiterationresults".
Characterstringsareenteredusingeithermatchingdouble(")orsingle(’)quotes,butare
printedusingdoublequotes(orsometimeswithoutquotes).TheyuseC-styleescapesequences,
using\astheescapecharacter,so\\isenteredandprintedas\\,andinsidedoublequotes"
isenteredas\". Otherusefulescapesequencesare\n,newline,\t,taband\b,backspace—see
?Quotesforafulllist.
Charactervectorsmaybeconcatenatedintoavectorbythec()function;examplesoftheir
usewillemergefrequently.
Thepaste()functiontakesanarbitrarynumberofargumentsandconcatenatesthemoneby
oneintocharacterstrings.Anynumbersgivenamongtheargumentsarecoercedintocharacter
strings inthe evidentway,thatis,inthesamewaytheywouldbeifthey wereprinted. . The
arguments arebydefault separatedintheresult by asingleblankcharacter,butthis canbe
changedbythenamedargument,sep=string,whichchangesittostring,possiblyempty.
Forexample
> labs s <- - paste(c("X","Y"), , 1:10, sep="")
makeslabsintothecharactervector
c("X1", "Y2", "X3", "Y4", "X5", , "Y6", "X7", , "Y8", "X9", "Y10")
Note particularly that t recycling g of short t lists takes place e here e too; thus s c("X","Y") ) is
repeated5timestomatchthesequence1:10.
3
2.7 Indexvectors;selectingandmodifyingsubsetsofadataset
Subsetsoftheelementsofavectormaybeselectedbyappendingtothenameofthevectoran
indexvectorinsquarebrackets. Moregenerallyanyexpressionthatevaluatestoavectormay
havesubsetsofitselementssimilarlyselectedbyappendinganindexvectorinsquarebrackets
immediatelyaftertheexpression.
Suchindexvectorscanbeanyoffourdistincttypes.
1. Alogicalvector. . Inthiscasetheindexvectorisrecycledtothesamelengthasthevector
fromwhichelementsaretobeselected. ValuescorrespondingtoTRUEintheindexvector
areselectedandthosecorrespondingtoFALSEareomitted. Forexample
> y y <- x[!is.na(x)]
creates(or re-creates)anobject ywhichwillcontainthenon-missingvalues of x,inthe
sameorder. Notethatifxhasmissingvalues,ywillbeshorterthanx. Also
> (x+1)[(!is.na(x)) & x>0] -> z
createsanobjectzandplacesinitthevaluesofthevectorx+1forwhichthecorresponding
valueinxwasbothnon-missingandpositive.
3
paste(...,collapse=ss)joinsthearguments intoasinglecharacter stringputtingss in between,e.g.,ss
<-"|". Therearemoretoolsforcharactermanipulation,seethehelpforsubandsubstring.
Chapter2:Simplemanipulations;numbersandvectors
11
2. Avectorofpositiveintegralquantities.Inthiscasethevaluesintheindexvectormustlie
intheset{1,2,...,length(x)}.Thecorrespondingelementsofthevectorareselectedand
concatenated,inthatorder,intheresult. Theindexvectorcanbeofanylengthandthe
resultisofthesamelengthastheindexvector. Forexamplex[6]isthesixthcomponent
ofxand
> x[1:10]
selectsthefirst10elementsofx(assuminglength(x)isnotlessthan10).Also
> c("x","y")[rep(c(1,2,2,1), , times=4)]
(anadmittedlyunlikelythingtodo)producesacharactervectoroflength16consistingof
"x","y","y","x"repeatedfourtimes.
3. Avectorofnegative e integralquantities. . Suchanindex x vectorspecifies thevalues tobe
excluded ratherthanincluded. Thus
> y y <- x[-(1:5)]
givesyallbutthefirstfiveelementsofx.
4. Avectorof f characterstrings. . This s possibility only applies whereanobjecthasa names
attributetoidentifyitscomponents.Inthiscaseasub-vectorofthenamesvectormaybe
usedinthesamewayasthepositiveintegrallabelsinitem2furtherabove.
> fruit <- c(5, 10, 1, 20)
> names(fruit) ) <- c("orange", , "banana", , "apple", , "peach")
> lunch <- fruit[c("apple","orange")]
The advantage is that t alphanumeric names s are e ofteneasier r to o remember than numeric
indices. Thisoptionisparticularly y usefulinconnectionwithdataframes,asweshallsee
later.
Anindexedexpressioncanalsoappearonthereceivingendofanassignment,inwhichcase
theassignment operationis performedonlyon those elements s of f the vector. . Theexpression
mustbeoftheformvector[index_vector]ashavinganarbitraryexpressioninplaceofthe
vectornamedoesnotmakemuchsensehere.
Forexample
> x[is.na(x)] ] <- 0
replacesanymissingvaluesinxbyzerosand
> y[y y < 0] <- -y[y < < 0]
hasthesameeffectas
> y y <- abs(y)
2.8 Othertypesofobjects
VectorsarethemostimportanttypeofobjectinR,butthereareseveralotherswhichwewill
meetmoreformallyinlatersections.
 matricesormoregenerallyarraysaremulti-dimensionalgeneralizationsofvectors. . Infact,
theyare vectorsthatcanbeindexedbytwoormoreindicesandwillbeprintedinspecial
ways. SeeChapter5[Arraysandmatrices],page18.
 factorsprovidecompactwaystohandlecategoricaldata.SeeChapter4[Factors],page16.
 lists s areageneralformof f vectorinwhichthevarious elementsneednotbeof the same
type,andareoftenthemselvesvectorsorlists.Listsprovideaconvenientwaytoreturnthe
resultsofastatisticalcomputation.SeeSection6.1[Lists],page26.
 dataframesarematrix-likestructures,inwhichthecolumnscanbeofdifferenttypes.Think
ofdataframesas‘datamatrices’withonerowperobservationalunitbutwith(possibly)
Chapter2:Simplemanipulations;numbersandvectors
12
bothnumericalandcategoricalvariables. Many y experiments arebest describedby data
frames: thetreatmentsarecategoricalbuttheresponseisnumeric. . SeeSection6.3[Data
frames],page27.
 functionsarethemselvesobjectsinRwhichcanbestoredintheproject’sworkspace.This
provides a simple e and d convenient way to extend R. See Chapter 10 0 [Writing g your own
functions],page42.
13
3 Objects,theirmodesandattributes
3.1 Intrinsicattributes: : modeandlength
Theentities Roperatesonaretechnicallyknownas objects. . Examplesarevectorsofnumeric
(real) orcomplexvalues,vectorsoflogicalvaluesandvectors of character strings. . These e are
knownas“atomic”structuressincetheircomponentsareallofthesametype,ormode,namely
numeric
1
,complex,logical,character andraw.
Vectors must have their values all of the samemode. . Thus s any givenvectormust be un-
ambiguouslyeitherlogical,numeric,complex,character orraw. . (Theonlyapparentexception
tothisruleisthespecial“value”listedasNAforquantitiesnotavailable,butinfactthereare
severaltypes of NA). . Note e that a vector can be empty and still have amode. . For r example
theemptycharacterstringvectorislistedas character(0)andtheemptynumericvector as
numeric(0).
Ralsooperatesonobjectscalledlists,whichareofmodelist. Theseareorderedsequences
ofobjectswhichindividuallycanbeof anymode. . lists s areknownas s “recursive”ratherthan
atomicstructuressincetheircomponentscanthemselvesbelistsintheirownright.
The other recursive structures are those ofmode e function and d expression. . Functions s are
theobjectsthatformpartoftheRsystemalongwithsimilaruserwrittenfunctions,whichwe
discussinsomedetaillater. ExpressionsasobjectsformanadvancedpartofRwhichwillnot
bediscussedinthisguide,exceptindirectlywhenwediscussformulaeusedwithmodelinginR.
Bythemodeofanobjectwemeanthebasictypeofitsfundamentalconstituents.Thisisa
specialcaseofa“property”ofanobject. Another r propertyofeveryobjectisits length. . The
functionsmode(object)andlength(object)canbeusedtofindoutthemodeandlengthof
anydefinedstructure
2
.
Furtherpropertiesofanobjectareusuallyprovidedbyattributes(object),seeSection3.3
[Getting and setting attributes], , page 14. . Because e of this, , mode e and length are e also called
“intrinsicattributes”ofanobject.
For example,if z isacomplexvectorof length100,theninanexpressionmode(z) is the
characterstring"complex"andlength(z)is100.
Rcatersforchangesofmodealmostanywhereitcouldbeconsideredsensibletodoso,(and
afewwhereitmightnotbe).Forexamplewith
> z z <- 0:9
wecouldput
> digits s <- as.character(z)
afterwhichdigitsisthecharactervectorc("0","1","2",...,"9").Afurthercoercion,or
changeofmode,reconstructsthenumericalvectoragain:
> d d <- as.integer(digits)
Nowdandzarethesame.
3
Thereisalargecollectionoffunctionsoftheformas.something()
foreithercoercionfromonemodetoanother,orforinvestinganobjectwithsomeotherattribute
itmaynotalreadypossess. Thereadershouldconsultthedifferenthelpfilestobecomefamiliar
withthem.
1
numericmodeisactuallyanamalgamoftwodistinctmodes,namelyintegeranddoubleprecision,asexplained
inthemanual.
2
Notehoweverthatlength(object)doesnotalwayscontainintrinsicusefulinformation,e.g.,whenobjectis
afunction.
3
In general, coercion from numeric c to character r and d back k again n will not t be e exactly reversible, because of
roundofferrorsinthecharacterrepresentation.
Chapter3:Objects,theirmodesandattributes
14
3.2 Changingthelengthofanobject
An“empty”objectmaystillhaveamode.Forexample
> e e <- numeric()
makeseanemptyvectorstructureofmodenumeric.Similarlycharacter()isaemptycharacter
vector,andsoon.Onceanobjectofanysizehasbeencreated,newcomponentsmaybeadded
toitsimplybygivingitanindexvalueoutsideitspreviousrange.Thus
> e[3] ] <- - 17
nowmakeseavectoroflength3,(thefirsttwocomponentsofwhichareatthispointbothNA).
Thisappliestoanystructureatall,providedthemodeoftheadditionalcomponent(s)agrees
withthemodeoftheobjectinthefirstplace.
Thisautomaticadjustmentoflengthsofanobjectisusedoften,forexampleinthescan()
functionforinput. (seeSection7.2[Thescan()function],page31.)
Converselytotruncatethesizeofanobjectrequiresonlyanassignmenttodoso. Henceif
alphaisanobjectoflength10,then
> alpha a <- alpha[2 * * 1:5]
makesitanobjectoflength5consistingofjusttheformercomponentswithevenindex. (The
oldindicesarenotretained,ofcourse.) Wecanthenretainjustthefirstthreevaluesby
> length(alpha) <- - 3
andvectorscanbeextended(bymissingvalues)inthesameway.
3.3 Gettingandsettingattributes
The function attributes(object) returns a list of allthe non-intrinsic attributes currently
defined for r that t object. . The e function attr(object,name) ) canbe e used to select t a a specific
attribute. Thesefunctionsare e rarelyused,exceptinratherspecialcircumstances whensome
newattributeisbeingcreatedforsomeparticularpurpose,forexampletoassociateacreation
dateoranoperatorwithanRobject.Theconcept,however,isveryimportant.
Somecareshouldbeexercisedwhenassigningordeletingattributessincetheyareanintegral
partoftheobjectsystemusedinR.
Whenitisusedonthelefthandsideofanassignmentitcanbeusedeithertoassociatea
newattributewithobjectortochangeanexistingone.Forexample
> attr(z, "dim") ) <- c(10,10)
allowsRtotreatzasifitwerea10-by-10matrix.
3.4 Theclassofanobject
AllobjectsinRhaveaclass,reportedbythefunctionclass. Forsimplevectorsthisisjustthe
mode,for example "numeric","logical", , "character"or"list",but t "matrix","array",
"factor"and"data.frame"areotherpossiblevalues.
Aspecialattributeknownastheclassoftheobjectisusedtoallowforanobject-oriented
style
4
ofprogramminginR.Forexampleifanobjecthasclass"data.frame",itwillbeprinted
ina certainway, the plot() functionwilldisplay it graphically in acertainway,andother
so-calledgenericfunctionssuchassummary()willreacttoitasanargumentinawaysensitive
toitsclass.
Toremovetemporarilytheeffectsofclass,usethefunctionunclass().Forexampleifwinter
hastheclass"data.frame"then
> winter
4
Adifferentstyleusing‘formal’or‘S4’classesisprovidedinpackagemethods.
Documents you may be interested
Documents you may be interested