Rev 26737 | Blame | Last modification | View Log | RSS feed
START-INFO-DIR-ENTRY* R FAQ: (R-FAQ). The R statistical system FAQ.END-INFO-DIR-ENTRYR FAQFrequently Asked Questions on RVersion 1.8-10, 2003-10-24ISBN 3-900051-01-1Kurt HornikTable of Contents*****************R FAQ1 Introduction1.1 Legalese1.2 Obtaining this document1.3 Citing this document1.4 Notation1.5 Feedback2 R Basics2.1 What is R?2.2 What machines does R run on?2.3 What is the current version of R?2.4 How can R be obtained?2.5 How can R be installed?2.5.1 How can R be installed (Unix)2.5.2 How can R be installed (Windows)2.5.3 How can R be installed (Macintosh)2.6 Are there Unix binaries for R?2.7 What documentation exists for R?2.8 Citing R2.9 What mailing lists exist for R?2.10 What is CRAN?2.11 Can I use R for commercial purposes?2.12 Why is R named R?3 R and S3.1 What is S?3.2 What is S-PLUS?3.3 What are the differences between R and S?3.3.1 Lexical scoping3.3.2 Models3.3.3 Others3.4 Is there anything R can do that S-PLUS cannot?3.5 What is R-plus?4 R Web Interfaces5 R Add-On Packages5.1 Which add-on packages exist for R?5.1.1 Add-on packages in R5.1.2 Add-on packages from CRAN5.1.3 Add-on packages from Omegahat5.1.4 Add-on packages from BioConductor5.1.5 Other add-on packages5.2 How can add-on packages be installed?5.3 How can add-on packages be used?5.4 How can add-on packages be removed?5.5 How can I create an R package?5.6 How can I contribute to R?6 R and Emacs6.1 Is there Emacs support for R?6.2 Should I run R from within Emacs?6.3 Debugging R from within Emacs7 R Miscellanea7.1 Why does R run out of memory?7.2 Why does sourcing a correct file fail?7.3 How can I set components of a list to NULL?7.4 How can I save my workspace?7.5 How can I clean up my workspace?7.6 How can I get eval() and D() to work?7.7 Why do my matrices lose dimensions?7.8 How does autoloading work?7.9 How should I set options?7.10 How do file names work in Windows?7.11 Why does plotting give a color allocation error?7.12 How do I convert factors to numeric?7.13 Are Trellis displays implemented in R?7.14 What are the enclosing and parent environments?7.15 How can I substitute into a plot label?7.16 What are valid names?7.17 Are GAMs implemented in R?7.18 Why is the output not printed when I source() a file?7.19 Why does outer() behave strangely with my function?7.20 Why does the output from anova() depend on the order of factors in the model?7.21 How do I produce PNG graphics in batch mode?7.22 How can I get command line editing to work?7.23 How can I turn a string into a variable?7.24 Why do lattice/trellis graphics not work?7.25 How can I sort the rows of a data frame?8 R Programming8.1 How should I write summary methods?8.2 How can I debug dynamically loaded code?8.3 How can I inspect R objects when debugging?8.4 How can I change compilation flags?9 R Bugs9.1 What is a bug?9.2 How to report a bug10 AcknowledgmentsR FAQ*****1 Introduction**************This document contains answers to some of the most frequently askedquestions about R.1.1 Legalese============This document is copyright (C) 1998-2003 by Kurt Hornik.This document is free software; you can redistribute it and/or modify itunder the terms of the GNU General Public License as published by the FreeSoftware Foundation; either version 2, or (at your option) any laterversion.This document is distributed in the hope that it will be useful, butWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITYor FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public Licensefor more details.A copy of the GNU General Public License is available via WWW at`http://www.gnu.org/copyleft/gpl.html'.You can also obtain it by writing to the Free Software Foundation, Inc., 59Temple Place -- Suite 330, Boston, MA 02111-1307, USA.1.2 Obtaining this document===========================The latest version of this document is always available from`http://www.ci.tuwien.ac.at/~hornik/R/'From there, you can obtain versions converted to plain ASCII text, DVI,GNU info, HTML, PDF, PostScript as well as the Texinfo source used forcreating all these formats using the GNU Texinfo system(http://texinfo.org/).You can also obtain the R FAQ from the `doc/FAQ' subdirectory of a CRANsite (*note What is CRAN?::).1.3 Citing this document========================In publications, please refer to this FAQ as Hornik (2003), "The R FAQ",and give the above, _official_ URL and the ISBN 3-900051-01-1.1.4 Notation============Everything should be pretty standard. `R>' is used for the R prompt, and a`$' for the shell prompt (where applicable).1.5 Feedback============Feedback is of course most welcome.In particular, note that I do not have access to Windows or Macintoshsystems. Features specific to the Windows and MacOS X ports of R aredescribed in the "R for Windows FAQ"(http://www.stats.ox.ac.uk/pub/R/rw-FAQ.html) and the "R for MacintoshFAQ/DOC" (http://cran.r-project.org/bin/macosx/RAqua-FAQ.html). If youhave information on Macintosh or Windows systems that you think should beadded to this document, please let me know.2 R Basics**********2.1 What is R?==============R is a system for statistical computation and graphics. It consists of alanguage plus a run-time environment with graphics, a debugger, access tocertain system functions, and the ability to run programs stored in scriptfiles.The design of R has been heavily influenced by two existing languages:Becker, Chambers & Wilks' S (*note What is S?::) and Sussman's Scheme(http://www.cs.indiana.edu/scheme-repository/home.html). Whereas theresulting language is very similar in appearance to S, the underlyingimplementation and semantics are derived from Scheme. *Note What are thedifferences between R and S?::, for further details.The core of R is an interpreted computer language which allows branchingand looping as well as modular programming using functions. Most of theuser-visible functions in R are written in R. It is possible for the userto interface to procedures written in the C, C++, or FORTRAN languages forefficiency. The R distribution contains functionality for a large numberof statistical procedures. Among these are: linear and generalized linearmodels, nonlinear regression models, time series analysis, classicalparametric and nonparametric tests, clustering and smoothing. There isalso a large set of functions which provide a flexible graphicalenvironment for creating various kinds of data presentations. Additionalmodules ("add-on packages") are available for a variety of specificpurposes (*note R Add-On Packages::).R was initially written by Ross Ihaka <Ross.Ihaka@R-project.org> andRobert Gentleman <Robert.Gentleman@R-project.org> at the Department ofStatistics of the University of Auckland in Auckland, New Zealand. Inaddition, a large group of individuals has contributed to R by sending codeand bug reports.Since mid-1997 there has been a core group (the "R Core Team") who canmodify the R source code CVS archive. The group currently consists of DougBates, John Chambers, Peter Dalgaard, Robert Gentleman, Kurt Hornik,Stefano Iacus, Ross Ihaka, Friedrich Leisch, Thomas Lumley, MartinMaechler, Duncan Murdoch, Paul Murrell, Martyn Plummer, Brian Ripley,Duncan Temple Lang, and Luke Tierney.R has a home page at `http://www.R-project.org/'. It is free softwaredistributed under a GNU-style copyleft, and an official part of the GNUproject ("GNU S").2.2 What machines does R run on?================================R is being developed for the Unix, Windows and Mac families of operatingsystems. Support for Mac OS Classic will end with the 1.7 series.The current version of R will configure and build under a number ofcommon Unix platforms including i386-freebsd, CPU-linux-gnu for the i386,alpha, arm, hppa, ia64, m68k, powerpc, and sparc CPUs (see e.g.`http://buildd.debian.org/build.php?&pkg=r-base'), i386-sun-solaris,powerpc-apple-darwin, mips-sgi-irix, alpha-dec-osf4, rs6000-ibm-aix,hppa-hp-hpux, and sparc-sun-solaris.If you know about other platforms, please drop us a note.2.3 What is the current version of R?=====================================The current released version is 1.8.0. Based on this`major.minor.patchlevel' numbering scheme, there are two developmentversions of R, working towards the next patch (`r-patched') and minor oreventually major (`r-devel') releases of R, respectively. Versionr-patched is for bug fixes mostly. New features are typically introducedin r-devel.2.4 How can R be obtained?==========================Sources, binaries and documentation for R can be obtained via CRAN, the"Comprehensive R Archive Network" (see *Note What is CRAN?::).Sources are also available via anonymous rsync. Usersync -rC --delete rsync.R-project.org::MODULE Rto create a copy of the source tree specified by MODULE in the subdirectory`R' of the current directory, where MODULE specifies one of the threeexisting flavors of the R sources, and can be one of `r-release' (currentreleased version), `r-patched' (patched released version), and `r-devel'(development version). The rsync trees are created directly from themaster CVS archive and are updated hourly. The `-C' and in the `rsync'command is to cause it to skip the CVS directories. Further information on`rsync' is available at `http://rsync.samba.org/rsync/'.The sources of the development version are also available via anonymousCVS. See `http://anoncvs.R-project.org' for more information.2.5 How can R be installed?===========================2.5.1 How can R be installed (Unix)-----------------------------------If binaries are available for your platform (see *Note Are there Unixbinaries for R?::), you can use these, following the instructions that comewith them.Otherwise, you can compile and install R yourself, which can be donevery easily under a number of common Unix platforms (see *Note Whatmachines does R run on?::). The file `INSTALL' that comes with the Rdistribution contains a brief introduction, and the "R Installation andAdministration" guide (*note What documentation exists for R?::) has fulldetails.Note that you need a FORTRAN compiler or `f2c' in addition to a Ccompiler to build R. Also, you need Perl version 5 to build the R objectdocumentations. (If this is not available on your system, you can obtain aPDF version of the object reference manual via CRAN.)In the simplest case, untar the R source code, change to the directorythus created, and issue the following commands (at the shell prompt):$ ./configure$ makeIf these commands execute successfully, the R binary and a shell scriptfront-end called `R' are created and copied to the `bin' directory. Youcan copy the script to a place where users can invoke it, for example to`/usr/local/bin'. In addition, plain text help pages as well as HTML andLaTeX versions of the documentation are built.Use `make dvi' to create DVI versions of the R manuals, such as`refman.dvi' (an R object reference index) and `R-exts.dvi', the "RExtension Writers Guide", in the `doc/manual' subdirectory. These filescan be previewed and printed using standard programs such as `xdvi' and`dvips'. You can also use `make pdf' to build PDF (Portable DocumentFormat) version of the manuals, and view these using e.g. Acrobat. Manualswritten in the GNU Texinfo system can also be converted to info filessuitable for reading online with Emacs or stand-alone GNU Info; use `makeinfo' to create these versions (note that this requires `makeinfo' version4).Finally, use `make check' to find out whether your R system workscorrectly.You can also perform a "system-wide" installation using `make install'.By default, this will install to the following directories:`${prefix}/bin'the front-end shell script`${prefix}/man/man1'the man page`${prefix}/lib/R'all the rest (libraries, on-line help system, ...). This is the "RHome Directory" (`R_HOME') of the installed system.In the above, `prefix' is determined during configuration (typically`/usr/local') and can be set by running `configure' with the option$ ./configure --prefix=/where/you/want/R/to/go(E.g., the R executable will then be installed into`/where/you/want/R/to/go/bin'.)To install DVI, info and PDF versions of the manuals, use `makeinstall-dvi', `make install-info' and `make install-pdf', respectively.2.5.2 How can R be installed (Windows)--------------------------------------The `bin/windows' directory of a CRAN site contains binaries for a basedistribution and a large number of add-on packages from CRAN to run onWindows 95, 98, ME, NT4, 2000, and XP (at least) on Intel and clones (butnot on other platforms). The Windows version of R was created by RobertGentleman, and is now being developed and maintained by Duncan Murdoch<murdoch@stats.uwo.ca> and Brian D. Ripley <Brian.Ripley@R-project.org>.For most installations the Windows installer program will be the easiesttool to use.See the "R for Windows FAQ"(http://www.stats.ox.ac.uk/pub/R/rw-FAQ.html) for more details.2.5.3 How can R be installed (Macintosh)----------------------------------------The `bin/macosx' directory of a CRAN site contains a standard Appleinstaller package named `RAqua.pkg.sit' compressed in Aladdin Stuffitformat. Once downloaded, uncompressed and executed, the installer willinstall the current non-developer release of R. RAqua is a native MacOSXDarwin version of R with an Aqua GUI. Inside `bin/macosx/X.Y' there areprebuilt binary packages to be used with RAqua corresponding to the "X.Y"release of R. The installation of these packages is available through the"Package" menu of the RAqua GUI. This port of R for MacOSX is maintainedby Stefano Iacus <Stefano.Iacus@R-project.org>. The "R for MacintoshFAQ/DOC" (http://cran.r-project.org/bin/macosx/RAqua-FAQ.html) has moredetails.The `bin/macos' directory of a CRAN site contains bin-hexed (`hqx') andstuffit (`sit') archives for a base distribution and a large number ofadd-on packages of R 1.7.1 to run under MacOS 8.6 to MacOS 9.2.2. Thisport of R for Macintosh is no longer supported.2.6 Are there Unix binaries for R?==================================The `bin/linux' directory of a CRAN site contains Debian stable/testingpackages for the i386 platform (now part of the Debian distribution andmaintained by Dirk Eddelbuettel), Mandrake 9.0/9.1 i386 packages by MicheleAlzetta, Red Hat 7.x/8.x/9 i386 packages by Martyn Plummer, SuSE7.3/8.0/8.1/8.2 i386 packages by Detlef Steuer, and VineLinux 2.6 i386packages by Susunu Tanimura.The Debian packages can be accessed through APT, the Debian packagemaintenance tool. Simply add the linedeb http://cran.R-project.org/bin/linux/debian DISTRIBUTION main(where DISTRIBUTION is either `stable' or `testing'; feel free to use aCRAN mirror instead of the master) to the file `/etc/apt/sources.list'.Once you have added that line the programs `apt-get', `apt-cache', and`dselect' (using the apt access method) will automatically detect andinstall updates of the R packages.No other binary distributions are currently publically available.2.7 What documentation exists for R?====================================Online documentation for most of the functions and variables in R exists,and can be printed on-screen by typing `help(NAME)' (or `?NAME') at the Rprompt, where NAME is the name of the topic help is sought for. (In thecase of unary and binary operators and control-flow special forms, the namemay need to be be quoted.)This documentation can also be made available as one reference manualfor on-line reading in HTML and PDF formats, and as hardcopy via LaTeX, see*Note How can R be installed?::. An up-to-date HTML version is alwaysavailable for web browsing at `http://stat.ethz.ch/R-manual/'.The R distribution also comes with the following manuals.* "An Introduction to R" (`R-intro') includes information on data types,programming elements, statistical modeling and graphics. Thisdocument is based on the "Notes on S-PLUS" by Bill Venables and DavidSmith.* "Writing R Extensions" (`R-exts') currently describes the process ofcreating R add-on packages, writing R documentation, R's system andforeign language interfaces, and the R API.* "R Data Import/Export" (`R-data') is a guide to importing andexporting data to and from R.* "The R Language Definition" (`R-lang'), a first version of the"Kernighan & Ritchie of R", explains evaluation, parsing, objectoriented programming, computing on the language, and so forth.* "R Installation and Administration" (`R-admin').Books on R includePeter Dalgaard (2002), "Introductory Statistics with R", Springer: NewYork, ISBN 0-387-95475-9.J. Fox (2002), "An R and S-PLUS Companion to Applied Regression", SagePublications, ISBN 0-761-92280-6 (softcover) or 0-761-92279-2(hardcover), `http://www.socsci.mcmaster.ca/jfox/Books/Companion/'.J. Maindonald and J. Braun (2003), "Data Analysis and Graphics UsingR", Cambridge University Press, ISBN 0-521-81336-0.S. M. Iacus and G. Masarotto (2002), "Laboratorio di statistica con R", McGraw-Hill, ISBN 88-386-6084-0 (in Italian).The bookW. N. Venables and B. D. Ripley (2002), "Modern Applied Statistics withS. Fourth Edition". Springer, ISBN 0-387-95457-0has a home page at `http://www.stats.ox.ac.uk/pub/MASS4/' providingadditional material. Its companion isW. N. Venables and B. D. Ripley (2000), "S Programming". Springer,ISBN 0-387-98966-8and provides an in-depth guide to writing software in the S language whichforms the basis of both the commercial S-PLUS and the Open Source R dataanalysis software systems. See`http://www.stats.ox.ac.uk/pub/MASS3/Sprog/' for more information.In addition to material written specifically or explicitly for R,documentation for S/S-PLUS (see *Note R and S::) can be used in combinationwith this FAQ (*note What are the differences between R and S?::).Introductory books includeP. Spector (1994), "An introduction to S and S-PLUS", Duxbury Press.A. Krause and M. Olsen (2002), "The Basics of S-PLUS" (Third Edition).Springer, ISBN 0-387-95456-2The bookJ. C. Pinheiro and D. M. Bates (2000), "Mixed-Effects Models in S andS-PLUS", Springer, ISBN 0-387-98957-0provides a comprehensive guide to the use of the *nlme* package for linearand nonlinear mixed-effects models. This has a home page at`http://nlme.stat.wisc.edu/MEMSS/'.As an example of how R can be used in teaching an advanced introductorystatistics course, seeD. Nolan and T. Speed (2000), "Stat Labs: Mathematical StatisticsThrough Applications", Springer Texts in Statistics, ISBN 0-387-98974-9This integrates theory of statistics with the practice of statisticsthrough a collection of case studies ("labs"), and uses R to analyze thedata. More information can be found at`http://www.stat.Berkeley.EDU/users/statlabs/'.Last, but not least, Ross' and Robert's experience in designing andimplementing R is described in Ihaka & Gentleman (1996), "R: A Language forData Analysis and Graphics", _Journal of Computational and GraphicalStatistics_, *5*, 299-314.An annotated bibliography (BibTeX format) of R-related publicationswhich includes most of the above references can be found at`http://www.R-project.org/doc/bib/R.bib'2.8 Citing R============To cite R in publications, use@Manual{,title = {R: A language and environment for statisticalcomputing},author = {{R Development Core Team}},organization = {R Foundation for Statistical Computing},address = {Vienna, Austria},year = 2003,note = {ISBN 3-900051-00-3},url = {http://www.R-project.org}}2.9 What mailing lists exist for R?===================================Thanks to Martin Maechler <Martin.Maechler@R-project.org>, there are fourmailing lists devoted to R.`R-announce'A moderated list for announcements about the development of R and theavailability of new code.`R-packages'A moderated list for announcements on the availability of new orenhanced contributed packages.`R-help'The `main' R mailing list, for discussion about problems and solutionsusing R, announcements (not covered by `R-announce' and `R-packages')about the development of R and the availability of new code,enhancements and patches to the source code and documentation of R,comparison and compatibility with S and S-PLUS, and for the posting ofnice examples and benchmarks.`R-devel'This list is for discussions about the future of R and pre-testing ofnew versions. It is meant for those who maintain an active position inthe development of R.Note that the R-announce and R-packages lists are gatewayed into R-help.Hence, you should subscribe to either of them only in case you are notsubscribed to R-help.Send email to <R-help@lists.R-project.org> to reach everyone on theR-help mailing list. To subscribe (or unsubscribe) to this list send`subscribe' (or `unsubscribe') in the _body_ of the message (not in thesubject!) to <R-help-request@lists.R-project.org>. Information about thelist can be obtained by sending an email with `info' as its contents to<R-help-request@lists.R-project.org>.Subscription and posting to the other lists is done analogously, with`R-help' replaced by `R-announce', `R-packages', and `R-devel',respectively.Subscriptions to the R-help and R-devel mailing lists are also availablein digest (plain or MIME) format, see the `doc/html/mail.html' file in CRANfor more information.It is recommended that you send mail to R-help rather than only to the RCore developers (who are also subscribed to the list, of course). This maysave them precious time they can use for constantly improving R, and willtypically also result in much quicker feedback for yourself.Of course, in the case of bug reports it would be very helpful to havecode which reliably reproduces the problem. Also, make sure that youinclude information on the system and version of R being used. See *Note RBugs:: for more details.Archives of the above three mailing lists are made available on the netin a monthly schedule via the `doc/html/mail.html' file in CRAN.Searchable archives of the lists are available via`http://maths.newcastle.edu.au/~rking/R/'.The R Core Team can be reached at <R-core@lists.R-project.org> forcomments and reports.2.10 What is CRAN?==================The "Comprehensive R Archive Network" (CRAN) is a collection of sites whichcarry identical material, consisting of the R distribution(s), thecontributed extensions, documentation for R, and binaries.The CRAN master site at TU Wien, Austria, can be found at the URL`http://cran.R-project.org/'and is currently being mirrored daily at`http://cran.at.R-project.org/' (TU Wien, Austria)`http://cran.au.R-project.org/' (PlanetMirror, Australia)`http://cran.br.R-project.org/' (Universidade Federal deParaná, Brazil)`http://cran.ch.R-project.org/' (ETH Zürich, Switzerland)`http://cran.de.R-project.org/' (APP, Germany)`http://cran.dk.R-project.org/' (SunSITE, Denmark)`http://cran.es.R-project.org/' (Spanish National ResearchNetwork, Madrid, Spain)`http://cran.hu.R-project.org/' (Semmelweis U, Hungary)`http://cran.uk.R-project.org/' (U of Bristol, UnitedKingdom)`http://cran.us.R-project.org/' (U of Wisconsin, USA)`http://cran.za.R-project.org/' (Rhodes U, South Africa)Please use the CRAN site closest to you to reduce network load.From CRAN, you can obtain the latest official release of R, dailysnapshots of R (copies of the current CVS trees), as gzipped and bzippedtar files, a wealth of additional contributed code, as well as prebuiltbinaries for various operating systems (Linux, MacOS Classic, MacOS X, andMS Windows). CRAN also provides access to documentation on R, existingmailing lists and the R Bug Tracking system.To "submit" to CRAN, simply upload to`ftp://cran.R-project.org/incoming/' and send an email to<cran@R-project.org>. Note that CRAN generally does not accept submissionsof precompiled binaries due to security reasons.*Note:* It is very important that you indicate the copyright(license) information (GPL, BSD, Artistic, ...) in your submission.Please always use the URL of the master site when referring to CRAN.2.11 Can I use R for commercial purposes?=========================================R is released under the GNU General Public License (GPL). If you have anyquestions regarding the legality of using R in any particular situation youshould bring it up with your legal counsel. We are in no position to offerlegal advice.It is the opinion of the R Core Team that one can use R for commercialpurposes (e.g., in business or in consulting). The GPL, like all OpenSource licenses, permits all and any use of the package. It only restrictsdistribution of R or of other programs containing code from R. This ismade clear in clause 6 ("No Discrimination Against Fields of Endeavor") ofthe Open Source Definition (http://www.opensource.org/docs/definition.html):The license must not restrict anyone from making use of the program ina specific field of endeavor. For example, it may not restrict theprogram from being used in a business, or from being used for geneticresearch.It is also explicitly stated in clause 0 of the GPL, which says in partActivities other than copying, distribution and modification are notcovered by this License; they are outside its scope. The act ofrunning the Program is not restricted, and the output from the Programis covered only if its contents constitute a work based on the Program.Most add-on packages, including all recommended ones, also explicitlyallow commercial use in this way. A few packages are restricted to"non-commercial use"; you should contact the author to clarify whetherthese may be used or seek the advice of your legal counsel.None of the discussion in this section constitutes legal advice. The RCore Team does not provide legal advice under any circumstances.2.12 Why is R named R?======================The name is partly based on the (first) names of the first two R authors(Robert Gentleman and Ross Ihaka), and partly a play on the name of theBell Labs language `S' (*note What is S?::).3 R and S*********3.1 What is S?==============S is a very high level language and an environment for data analysis andgraphics. In 1998, the Association for Computing Machinery (ACM) presentedits Software System Award to John M. Chambers, the principal designer of S,forthe S system, which has forever altered the way people analyze,visualize, and manipulate data ...S is an elegant, widely accepted, and enduring software system, withconceptual integrity, thanks to the insight, taste, and effort of JohnChambers.The evolution of the S language is characterized by four books by JohnChambers and coauthors, which are also the primary references for S.* Richard A. Becker and John M. Chambers (1984), "S. An InteractiveEnvironment for Data Analysis and Graphics," Monterey: Wadsworth andBrooks/Cole.This is also referred to as the "_Brown Book_", and of historicalinterest only.* Richard A. Becker, John M. Chambers and Allan R. Wilks (1988), "The NewS Language," London: Chapman & Hall.This book is often called the "_Blue Book_", and introduced what isnow known as S version 2.* John M. Chambers and Trevor J. Hastie (1992), "Statistical Models inS," London: Chapman & Hall.This is also called the "_White Book_", and introduced S version 3,which added structures to facilitate statistical modeling in S.* John M. Chambers (1998), "Programming with Data," New York: Springer,ISBN 0-387-98503-4(<http://cm.bell-labs.com/cm/ms/departments/sia/Sbook/>).This "_Green Book_" describes version 4 of S, a major revision of Sdesigned by John Chambers to improve its usefulness at every stage ofthe programming process.See `http://cm.bell-labs.com/cm/ms/departments/sia/S/history.html' forfurther information on "Stages in the Evolution of S".There is a huge amount of user-contributed code for S, available at theS Repository (http://lib.stat.cmu.edu/S/) at CMU.3.2 What is S-PLUS?===================S-PLUS is a value-added version of S sold by Insightful Corporation. Basedon the S language, S-PLUS provides functionality in a wide variety ofareas, including robust regression, modern non-parametric regression, timeseries, survival analysis, multivariate analysis, classical statisticaltests, quality control, and graphics drivers. Add-on modules addadditional capabilities for wavelet analysis, spatial statistics, GARCHmodels, and design of experiments.See the Insightful S-PLUS page(http://www.insightful.com/products/splus/) for further information.3.3 What are the differences between R and S?=============================================We can regard S as a language with three current implementations or"engines", the "old S engine" (S version 3; S-PLUS 3.x and 4.x), the "new Sengine" (S version 4; S-PLUS 5.x and above), and R. Given thisunderstanding, asking for "the differences between R and S" really amountsto asking for the specifics of the R implementation of the S language,i.e., the difference between the R and S _engines_.For the remainder of this section, "S" refers to the S engines and notthe S language.3.3.1 Lexical scoping---------------------Contrary to other implementations of the S language, R has adopted theevaluation model of Scheme.This difference becomes manifest when _free_ variables occur in afunction. Free variables are those which are neither formal parameters(occurring in the argument list of the function) nor local variables(created by assigning to them in the body of the function). Whereas S(like C) by default uses _static_ scoping, R (like Scheme) has adopted_lexical_ scoping. This means the values of free variables are determinedby a set of global variables in S, but in R by the bindings that were ineffect at the time the function was created.Consider the following function:cube <- function(n) {sq <- function() n * nn * sq()}Under S, `sq()' does not "know" about the variable `n' unless it isdefined globally:S> cube(2)Error in sq(): Object "n" not foundDumpedS> n <- 3S> cube(2)[1] 18In R, the "environment" created when `cube()' was invoked is also lookedin:R> cube(2)[1] 8As a more "interesting" real-world problem, suppose you want to write afunction which returns the density function of the r-th order statisticfrom a sample of size n from a (continuous) distribution. For simplicity,we shall use both the cdf and pdf of the distribution as explicitarguments. (Example compiled from various postings by Luke Tierney.)The S-PLUS documentation for `call()' basically suggests the following:dorder <- function(n, r, pfun, dfun) {f <- function(x) NULLcon <- round(exp(lgamma(n + 1) - lgamma(r) - lgamma(n - r + 1)))PF <- call(substitute(pfun), as.name("x"))DF <- call(substitute(dfun), as.name("x"))f[[length(f)]] <-call("*", con,call("*", call("^", PF, r - 1),call("*", call("^", call("-", 1, PF), n - r),DF)))f}Rather tricky, isn't it? The code uses the fact that in S, functions arejust lists of special mode with the function body as the last argument, andhence does not work in R (one could make the idea work, though).A version which makes heavy use of `substitute()' and seems to workunder both S and R isdorder <- function(n, r, pfun, dfun) {con <- round(exp(lgamma(n + 1) - lgamma(r) - lgamma(n - r + 1)))eval(substitute(function(x) K * PF(x)^a * (1 - PF(x))^b * DF(x),list(PF = substitute(pfun), DF = substitute(dfun),a = r - 1, b = n - r, K = con)))}(the `eval()' is not needed in S).However, in R there is a much easier solution:dorder <- function(n, r, pfun, dfun) {con <- round(exp(lgamma(n + 1) - lgamma(r) - lgamma(n - r + 1)))function(x) {con * pfun(x)^(r - 1) * (1 - pfun(x))^(n - r) * dfun(x)}}This seems to be the "natural" implementation, and it works because thefree variables in the returned function can be looked up in the definingenvironment (this is lexical scope).Note that what you really need is the function _closure_, i.e., the bodyalong with all variable bindings needed for evaluating it. Since in theabove version, the free variables in the value function are not modified,you can actually use it in S as well if you abstract out the closureoperation into a function `MC()' (for "make closure"):dorder <- function(n, r, pfun, dfun) {con <- round(exp(lgamma(n + 1) - lgamma(r) - lgamma(n - r + 1)))MC(function(x) {con * pfun(x)^(r - 1) * (1 - pfun(x))^(n - r) * dfun(x)},list(con = con, pfun = pfun, dfun = dfun, r = r, n = n))}Given the appropriate definitions of the closure operator, this works inboth R and S, and is much "cleaner" than a substitute/eval solution (or onewhich overrules the default scoping rules by using explicit access toevaluation frames, as is of course possible in both R and S).For R, `MC()' simply isMC <- function(f, env) f(lexical scope!), a version for S isMC <- function(f, env = NULL) {env <- as.list(env)if (mode(f) != "function")stop(paste("not a function:", f))if (length(env) > 0 && any(names(env) == ""))stop(paste("not all arguments are named:", env))fargs <- if(length(f) > 1) f[1:(length(f) - 1)] else NULLfargs <- c(fargs, env)if (any(duplicated(names(fargs))))stop(paste("duplicated arguments:", paste(names(fargs)),collapse = ", "))fbody <- f[length(f)]cf <- c(fargs, fbody)mode(cf) <- "function"return(cf)}Similarly, most optimization (or zero-finding) routines need somearguments to be optimized over and have other parameters that depend on thedata but are fixed with respect to optimization. With R scoping rules,this is a trivial problem; simply make up the function with the requireddefinitions in the same environment and scoping takes care of it. With S,one solution is to add an extra parameter to the function and to theoptimizer to pass in these extras, which however can only work if theoptimizer supports this.Lexical scoping allows using function closures and maintaining localstate. A simple example (taken from Abelson and Sussman) is obtained bytyping `demo("scoping")' at the R prompt. Further information is providedin the standard R reference "R: A Language for Data Analysis and Graphics"(*note What documentation exists for R?::) and in Robert Gentleman and RossIhaka (2000), "Lexical Scope and Statistical Computing", _Journal ofComputational and Graphical Statistics_, *9*, 491-508.Lexical scoping also implies a further major difference. Whereas Sstores all objects as separate files in a directory somewhere (usually`.Data' under the current directory), R does not. All objects in R arestored internally. When R is started up it grabs a piece of memory anduses it to store the objects. R performs its own memory management of thispiece of memory, growing and shrinking its size as needed. Havingeverything in memory is necessary because it is not really possible toexternally maintain all relevant "environments" of symbol/value pairs.This difference also seems to make R _faster_ than S.The down side is that if R crashes you will lose all the work for thecurrent session. Saving and restoring the memory "images" (the functionsand data stored in R's internal memory at any time) can be a bit slow,especially if they are big. In S this does not happen, because everythingis saved in disk files and if you crash nothing is likely to happen tothem. (In fact, one might conjecture that the S developers felt that theprice of changing their approach to persistent storage just to accommodatelexical scope was far too expensive.) Hence, when doing important work,you might consider saving often (see *Note How can I save my workspace?::)to safeguard against possible crashes. Other possibilities are loggingyour sessions, or have your R commands stored in text files which can beread in using `source()'.*Note:* If you run R from within Emacs (see *Note R and Emacs::), youcan save the contents of the interaction buffer to a file andconveniently manipulate it using `ess-transcript-mode', as well assave source copies of all functions and data used.3.3.2 Models------------There are some differences in the modeling code, such as* Whereas in S, you would use `lm(y ~ x^3)' to regress `y' on `x^3', inR, you have to insulate powers of numeric vectors (using `I()'), i.e.,you have to use `lm(y ~ I(x^3))'.* The glm family objects are implemented differently in R and S. Thesame functionality is available but the components have differentnames.* Option `na.action' is set to `"na.omit"' by default in R, but not setin S.* Terms objects are stored differently. In S a terms object is anexpression with attributes, in R it is a formula with attributes. Theattributes have the same names but are mostly stored differently. Themajor difference in functionality is that a terms object issubscriptable in S but not in R. If you can't imagine why this wouldmatter then you don't need to know.* Finally, in R `y~x+0' is an alternative to `y~x-1' for specifying amodel with no intercept. Models with no parameters at all can bespecified by `y~0'.3.3.3 Others------------Apart from lexical scoping and its implications, R follows the S languagedefinition in the Blue and White Books as much as possible, and hencereally is an "implementation" of S. There are some intentional differenceswhere the behavior of S is considered "not clean". In general, therationale is that R should help you detect programming errors, while at thesame time being as compatible as possible with S.Some known differences are the following.* In R, if `x' is a list, then `x[i] <- NULL' and `x[[i]] <- NULL'remove the specified elements from `x'. The first of these isincompatible with S, where it is a no-op. (Note that you can setelements to `NULL' using `x[i] <- list(NULL)'.)* In S, the functions named `.First' and `.Last' in the `.Data'directory can be used for customizing, as they are executed at thevery beginning and end of a session, respectively.In R, the startup mechanism is as follows. R first sources the systemstartup file ``$R_HOME'/library/base/R/Rprofile'. Then, it searchesfor a site-wide startup profile unless the command line option`--no-site-file' was given. The name of this file is taken from thevalue of the `R_PROFILE' environment variable. If that variable isunset, the default is ``$R_HOME'/etc/Rprofile.site'(``$R_HOME'/etc/Rprofile' in versions prior to 1.4.0). This code isloaded in package *base*. Then, unless `--no-init-file' was given, Rsearches for a file called `.Rprofile' in the current directory or inthe user's home directory (in that order) and sources it into the userworkspace. It then loads a saved image of the user workspace from`.RData' in case there is one (unless `--no-restore' was specified).If needed, the functions `.First()' and `.Last()' should be defined inthe appropriate startup profiles.* In R, `T' and `F' are just variables being set to `TRUE' and `FALSE',respectively, but are not reserved words as in S and hence can beoverwritten by the user. (This helps e.g. when you have factors withlevels `"T"' or `"F"'.) Hence, when writing code you should alwaysuse `TRUE' and `FALSE'.* In R, `dyn.load()' can only load _shared objects_, as created forexample by `R CMD SHLIB'.* In R, `attach()' currently only works for lists and data frames, butnot for directories. (In fact, `attach()' also works for R data filescreated with `save()', which is analogous to attaching directories inS.) Also, you cannot attach at position 1.* Categories do not exist in R, and never will as they are deprecated nowin S. Use factors instead.* In R, `For()' loops are not necessary and hence not supported.* In R, `assign()' uses the argument `envir=' rather than `where=' as inS.* The random number generators are different, and the seeds havedifferent length.* R passes integer objects to C as `int *' rather than `long *' as in S.* R has no single precision storage mode. However, as of version 0.65.1,there is a single precision interface to C/FORTRAN subroutines.* By default, `ls()' returns the names of the objects in the current(under R) and global (under S) environment, respectively. For example,givenx <- 1; fun <- function() {y <- 1; ls()}then `fun()' returns `"y"' in R and `"x"' (together with the rest ofthe global environment) in S.* R allows for zero-extent matrices (and arrays, i.e., some elements ofthe `dim' attribute vector can be 0). This has been determined auseful feature as it helps reducing the need for special-case tests forempty subsets. For example, if `x' is a matrix, `x[, FALSE]' is not`NULL' but a "matrix" with 0 columns. Hence, such objects need to betested for by checking whether their `length()' is zero (which worksin both R and S), and not using `is.null()'.* Named vectors are considered vectors in R but not in S (e.g.,`is.vector(c(a = 1:3))' returns `FALSE' in S and `TRUE' in R).* Data frames are not considered as matrices in R (i.e., if `DF' is adata frame, then `is.matrix(DF)' returns `FALSE' in R and `TRUE' in S).* R by default uses treatment contrasts in the unordered case, whereas Suses the Helmert ones. This is a deliberate difference reflecting theopinion that treatment contrasts are more natural.* In R, the argument of a replacement function which corresponds to theright hand side must be named `value'. E.g., `f(a) <- b' is evaluatedas `a <- "f<-"(a, value = b)'. S always takes the last argument,irrespective of its name.* In S, `substitute()' searches for names for substitution in the givenexpression in three places: the actual and the default arguments ofthe matching call, and the local frame (in that order). R looks inthe local frame only, with the special rule to use a "promise" if avariable is not evaluated. Since the local frame is initialized withthe actual arguments or the default expressions, this is usuallyequivalent to S, until assignment takes place.* In S, the index variable in a `for()' loop is local to the inside ofthe loop. In R it is local to the environment where the `for()'statement is executed.* In S, `tapply(simplify=TRUE)' returns a vector where R returns aone-dimensional array (which can have named dimnames).* In S(-PLUS) the C locale is used, whereas in R the current operatingsystem locale is used for determining which characters arealphanumeric and how they are sorted. This affects the set of validnames for R objects (for example accented chars may be allowed in R)and ordering in sorts and comparisons (such as whether `"aA" < "Bb"' istrue or false). From version 1.2.0 the locale can be (re-)set in R bythe `Sys.setlocale()' function.* In S, `missing(ARG)' remains `TRUE' if ARG is subsequently modified;in R it doesn't.* From R version 1.3.0, `data.frame' strips `I()' when creating (column)names.* In R, the string `"NA"' is not treated as a missing value in acharacter variable. Use `as.character(NA)' to create a missingcharacter value.* R disallows repeated formal arguments in function calls.There are also differences which are not intentional, and result frommissing or incorrect code in R. The developers would appreciate hearingabout any deficiencies you may find (in a written report fully documentingthe difference as you see it). Of course, it would be useful if you wereto implement the change yourself and make sure it works.3.4 Is there anything R can do that S-PLUS cannot?==================================================Since almost anything you can do in R has source code that you could portto S-PLUS with little effort there will never be much you can do in R thatyou couldn't do in S-PLUS if you wanted to. (Note that using lexicalscoping may simplify matters considerably, though.)R offers several graphics features that S-PLUS does not, such as finerhandling of line types, more convenient color handling (via palettes),gamma correction for color, and, most importantly, mathematical annotationin plot texts, via input expressions reminiscent of TeX constructs. Seethe help page for `plotmath', which features an impressive on-line example.More details can be found in Paul Murrell and Ross Ihaka (2000), "AnApproach to Providing Mathematical Annotation in Plots", _Journal ofComputational and Graphical Statistics_, *9*, 582-599.3.5 What is R-plus?===================There is no such thing.4 R Web Interfaces*******************Rweb* is developed and maintained by Jeff Banfield<jeff@math.montana.edu>. The Rweb Home Page(http://www.math.montana.edu/Rweb/) provides access to all three versionsof Rweb--a simple text entry form that returns output and graphs, a moresophisticated Javascript version that provides a multiple windowenvironment, and a set of point and click modules that are useful forintroductory statistics courses and require no knowledge of the R language.All of the Rweb versions can analyze Web accessible datasets if a URL isprovided.The paper "Rweb: Web-based Statistical Analysis", providing a detailedexplanation of the different versions of Rweb and an overview of how Rwebworks, was published in the Journal of Statistical Software(`http://www.stat.ucla.edu/journals/jss/v04/i01/').Ulf Bartel <ulfi@cs.tu-berlin.de> is working on *R-Online*, a simpleon-line programming environment for R which intends to make the first stepsin statistical programming with R (especially with time series) as easy aspossible. There is no need for a local installation since the onlyrequirement for the user is a JavaScript capable browser. See`http://osvisions.com/r-online/' for more information.*CGIwithR* is an R add-on package by David Firth<david.firth@nuffield.ox.ac.uk> and has its home page at`http://www.stats.ox.ac.uk/~firth/CGIwithR/index.html'. It provides somesimple extensions to R to facilitate running R scripts through the CGIinterface to a web server. It is easily installed using Apache under Linuxand in principle should run on any platform that supports R and a webserver provided that the installer has the necessary security permissions.*Rcgi* is a CGI WWW interface to R by Mark J. Ray<mjr@stats.mth.uea.ac.uk>. It had the ability to use "embedded code": youcould mix user input and code, allowing the HTML author to do anything fromload in data sets to enter most of the commands for users without writingCGI scripts. Graphical output was possible in PostScript or GIF formatsand the executed code was presented to the user for revision. However, itis not clear if the project is still active and recent attempts to contactthe author or find the package have failed.5 R Add-On Packages*******************5.1 Which add-on packages exist for R?======================================5.1.1 Add-on packages in R--------------------------The R distribution comes with the following extra packages:*ctest*A collection of Classical TESTs, including the Ansari-Bradley,Bartlett, chi-squared, Fisher, Kruskal-Wallis, Kolmogorov-Smirnov, t,and Wilcoxon tests.*eda*Exploratory Data Analysis. Currently only contains functions forrobust line fitting, and median polish and smoothing.*grid*A rewrite of the graphics layout capabilities, plus some support forinteraction. (Added in R 1.8.0).*lqs*Resistant regression and covariance estimation.*methods*Formally defined methods and classes for R objects, plus otherprogramming tools, as described in the Green Book.*mle*Generic (smooth) likelihood maximization and profiling. (Added in R1.8.0).*modreg*MODern REGression: smoothing and local methods.*mva*MultiVariate Analysis. Currently contains code for principalcomponents, canonical correlations, metric multidimensional scaling,factor analysis, and hierarchical and k-means clustering.*nls*Nonlinear regression routines.*splines*Regression spline functions and classes.*stepfun*Code for dealing with STEP FUNctions, including empirical cumulativedistribution functions.*tcltk*Interface and language bindings to Tcl/Tk GUI elements.*tools*Tools for package development and administration.*ts*Time Series.5.1.2 Add-on packages from CRAN-------------------------------The following packages are available from the CRAN `src/contrib' area.(Packages denoted as _Recommended_ are to be included in all binarydistributions of R.)*AnalyzeFMRI*Functions for I/O, visualisation and analysis of functional MagneticResonance Imaging (fMRI) datasets stored in the ANALYZE format.*Bhat*Functions for general likelihood exploration (MLE, MCMC, CIs).*CGIwithR*Facilities for the use of R to write CGI scripts.*CircStats*Circular Statistics, from "Topics in Circular Statistics" by S. RaoJammalamadaka and A. SenGupta, 2001, World Scientific.*CoCoAn*Constrained Correspondence Analysis.*DAAG*Various data sets used in examples and exercises in "Data Analysis andGraphics Using R" by John H. Maindonald and W. John Brown, 2003.*DBI*A common database interface (DBI) class and method definitions. Allclasses in this package are virtual and need to be extended by thevarious DBMS implementations.*Davies*Functions for the Davies quantile function and the Generalized Lambdadistribution.*Design*Regression modeling, testing, estimation, validation, graphics,prediction, and typesetting by storing enhanced model design attributesin the fit. Design is a collection of about 180 functions that assistand streamline modeling, especially for biostatistical andepidemiologic applications. It also contains new functions for binaryand ordinal logistic regression models and the Buckley-James multipleregression model for right-censored responses, and implementspenalized maximum likelihood estimation for logistic and ordinarylinear models. Design works with almost any regression model, but itwas especially written to work with logistic regression, Coxregression, accelerated failure time models, ordinary linear models,and the Buckley-James model.*Devore5*Data sets and sample analyses from "Probability and Statistics forEngineering and the Sciences (5th ed)" by Jay L. Devore, 2000, Duxbury.*Devore6*Data sets and sample analyses from "Probability and Statistics forEngineering and the Sciences (6th ed)" by Jay L. Devore, 2003, Duxbury.*GRASS*An interface between the GRASS geographical information system and R,based on starting R from within the GRASS environment and chosenLOCATION_NAME and MAPSET. Wrapper and helper functions are providedfor a range of R functions to match the interface metadata structures.*GenKern*Functions for generating and manipulating generalised binned kerneldensity estimates.*Hmisc*Functions useful for data analysis, high-level graphics, utilityoperations, functions for computing sample size and power, importingdatasets, imputing missing values, advanced table making, variableclustering, character string manipulation, conversion of S objects toLaTeX code, recoding variables, and bootstrap repeated measuresanalysis.*HyperbolicDist*Basic functions for the hyperbolic distribution: probability densityfunction, distribution function, quantile function, a routine forgenerating observations from the hyperbolic, and a function for fittingthe hyperbolic distribution to data.*ISwR*Data sets for "Introductory Statistics with R" by Peter Dalgaard,2002, Springer.*KMsurv*Data sets and functions for "Survival Analysis, Techniques for Censoredand Truncated Data" by Klein and Moeschberger, 1997, Springer.*KernSmooth*Functions for kernel smoothing (and density estimation) correspondingto the book "Kernel Smoothing" by M. P. Wand and M. C. Jones, 1995._Recommended_.*MASS*Functions and datasets from the main package of Venables and Ripley,"Modern Applied Statistics with S". Contained in the `VR' bundle._Recommended_.*MCMCpack*Markov chain Monte Carlo (MCMC) package: functions for posteriorsimulation for a number of statistical models.*MPV*Data sets from the book "Introduction to Linear Regression Analysis"by D. C. Montgomery, E. A. Peck, and C. G. Vining, 2001, John Wiley andSons.*Matrix*A Matrix package.*NISTnls*A set of test nonlinear least squares examples from NIST, the U.S.National Institute for Standards and Technology.*Oarray*Arrays with arbitrary offsets.*PHYLOGR*Manipulation and analysis of phylogenetically simulated data sets (asobtained from PDSIMUL in package PDAP) and phylogenetically-basedanalyses using GLS.*PTAk*A multiway method to decompose a tensor (array) of any order, as ageneralisation of SVD also supporting non-identity metrics andpenalisations. Also includes some other multiway methods.*R2HTML*Functions for exporting R objects & graphics in an HTML document.*RArcInfo*Functions to import Arc/Info V7.x coverages and data.*RColorBrewer*ColorBrewer palettes for drawing nice maps shaded according to avariable.*RMySQL*An interface between R and the MySQL database system.*RODBC*An ODBC database interface.*ROracle*Oracle Database Interface driver for R. Uses the ProC/C++ embeddedSQL.*RQuantLib*Provides access to (some) of the QuantLib functions from within R;currently limited to some Option pricing and analysis functions. TheQuantLib project aims to provide a comprehensive software framework forquantitative finance.*RSQLite*Database Interface R driver for SQLite. Embeds the SQLite databaseengine in R.*RSvgDevice*A graphics device for R that uses the new w3.org XML standard forScalable Vector Graphics.*RadioSonde*A collection of programs for reading and plotting SKEW-T,log p diagramsand wind profiles for data collected by radiosondes (the typicalweather balloon-borne instrument).*RandomFields*Creating random fields using various methods.*Rcmdr*A platform-independent basic-statistics GUI (graphical user interface)for R, based on the *tcltk* package.*RmSQL*An interface between R and the mSQL database system.*Rwave*An environment for the time-frequency analysis of 1-D signals (andespecially for the wavelet and Gabor transforms of noisy signals),based on the book "Practical Time-Frequency Analysis: Gabor and WaveletTransforms with an Implementation in S" by Rene Carmona, Wen L. Hwangand Bruno Torresani, 1998, Academic Press.*SASmixed*Data sets and sample linear mixed effects analyses corresponding to theexamples in "SAS System for Mixed Models" by R. C. Littell, G. A.Milliken, W. W. Stroup and R. D. Wolfinger, 1996, SAS Institute.*SenSrivastava*Collection of datasets from "Regression Analysis, Theory, Methods andApplications" by A. Sen and M. Srivastava, 1990, Springer-Verlag.*SparseM*Basic linear algebra for sparse matrices.*StatDataML*Read and write StatDataML.*SuppDists*Ten distributions supplementing those built into R (Inverse Gauss,Kruskal-Wallis, Kendall's Tau, Friedman's chi squared, Spearman's rho,maximum F ratio, the Pearson product moment correlation coefficiant,Johnson distributions, normal scores and generalized hypergeometricdistributions).*VLMC*Functions, classes & methods for estimation, prediction, and simulation(bootstrap) of VLMC (Variable Length Markov Chain) models.*VaR*Methods for calculation of Value at Risk (VaR).*XML*Facilities for reading XML documents and DTDs.*abind*Combine multi-dimensional arrays.*acepack*ACE (Alternating Conditional Expectations) and AVAS (Additivity andVAriance Stabilization for regression) methods for selecting regressiontransformations.*adapt*Adaptive quadrature in up to 20 dimensions.*ade4*Multivariate data analysis and graphical display.*agce*Analysis of growth curve experiments.*akima*Linear or cubic spline interpolation for irregularly gridded data.*amap*Another Multidimensional Analysis Package.*anm*Analog model for statistical/empirical downscaling.*ape*Analyses of Phylogenetics and Evolution, providing functions forreading and plotting phylogenetic trees in parenthetic format(standard Newick format), analyses of comparative data in aphylogenetic framework, analyses of diversification andmacroevolution, computing distances from allelic and nucleotide data,reading nucleotide sequences from GenBank via internet, and severaltools such as Mantel's test, computation of minimum spanning tree, orthe population parameter theta based on various approaches.*ash*David Scott's ASH routines for 1D and 2D density estimation.*aws*Functions to perform adaptive weights smoothing.*bim*Bayesian interval mapping diagnostics: functions to interpret QTLCartand Bmapqtl samples.*bindata*Generation of correlated artificial binary data.*blighty*Function for drawing the coastline of the United Kingdom.*boolean*Boolean logit and probit: a procedure for testing Boolean hypotheses.*boot*Functions and datasets for bootstrapping from the book "BootstrapMethods and Their Applications" by A. C. Davison and D. V. Hinkley,1997, Cambridge University Press. _Recommended_.*bootstrap*Software (bootstrap, cross-validation, jackknife), data and errata forthe book "An Introduction to the Bootstrap" by B. Efron and R.Tibshirani, 1993, Chapman and Hall.*bqtl*QTL mapping toolkit for inbred crosses and recombinant inbred lines.Includes maximum likelihood and Bayesian tools.*brlr*Bias-reduced logistic regression: fits logistic regression models bymaximum penalized likelihood.*car*Companion to Applied Regression, containing functions for appliedregession, linear models, and generalized linear models, with anemphasis on regression diagnostics, particularly graphical diagnosticmethods.*cat*Analysis of categorical-variable datasets with missing values.*cclust*Convex clustering methods, including k-means algorithm, on-line updatealgorithm (Hard Competitive Learning) and Neural Gas algorithm (SoftCompetitive Learning) and calculation of several indexes for findingthe number of clusters in a data set.*cfa*Analysis of configuration frequencies.*chron*A package for working with chronological objects (times and dates).*class*Functions for classification (k-nearest neighbor and LVQ). Containedin the `VR' bundle. _Recommended_.*classPP*Projection Pursuit for supervised classification.*clim.pact*Climate analysis and downscaling for monthly and daily data.*clines*Calculates Contour Lines.*cluster*Functions for cluster analysis. _Recommended_.*cmprsk*Estimation, testing and regression modeling of subdistributionfunctions in competing risks.*cobs*Constrained B-splines: qualitatively constrained (regression) smoothingvia linear programming.*coda*Output analysis and diagnostics for Markov Chain Monte Carlo (MCMC)simulations.*combinat*Combinatorics utilities.*conf.design*A series of simple tools for constructing and manipulating confoundedand fractional factorial designs.*cramer*Routine for the multivariate nonparametric Cramer test.*date*Functions for dealing with dates. The most useful of them accepts avector of input dates in any of the forms `8/30/53', `30Aug53', `30August 1953', ..., `August 30 53', or any mixture of these.*dblcens*Calculates the NPMLE of the survival distribution for doubly censoreddata.*deal*Bayesian networks with continuous and/or discrete variables can belearned and compared from data.*deldir*Calculates the Delaunay triangulation and the Dirichlet or Voronoitesselation (with respect to the entire plane) of a planar point set.*diamonds*Functions for illustrating aperture-4 diamond partitions in the plane,or on the surface of an octahedron or icosahedron, for use as analysisor sampling grids.*dichromat*Color schemes for dichromats: collapse red-green distinctions tosimulate the effects of colour-blindness.*diptest*Compute Hartigan's dip test statistic for unimodality.*dispmod*Functions for modelling dispersion in GLMs.*dr*Functions, methods, and datasets for fitting dimension reductionregression, including pHd and inverse regression methods SIR and SAVE.*dse*Dynamic System Estimation, a multivariate time series package.Contains *dse1* (the base system, including multivariate ARMA and statespace models), *dse2* (extensions for evaluating estimationtechniques, forecasting, and for evaluating forecasting model),*tframe* (functions for writing code that is independent of therepresentation of time). and *setRNG* (a mechanism for generating thesame random numbers in S and R).*e1071*Miscellaneous functions used at the Department of Statistics at TU Wien(E1071), including moments, short-time Fourier transforms, IndependentComponent Analysis, Latent Class Analysis, support vector machines, andfuzzy clustering, shortest path computation, bagged clustering, andsome more.*effects*Graphical and tabular effect displays, e.g., of interactions, forlinear and generalised linear models.*eha*A package for survival and event history analysis.*ellipse*Package for drawing ellipses and ellipse-like confidence regions.*emme2*Functions to read from and write to an EMME/2 databank.*emplik*Empirical likelihood ratio for means/quantiles/hazards from possiblyright censored data.*evd*Functions for extreme value distributions. Extends simulation,distribution, quantile and density functions to univariate, bivariateand (for simulation) multivariate parametric extreme valuedistributions, and provides fitting functions which calculate maximumlikelihood estimates for univariate and bivariate models.*exactLoglinTest*Monte Carlo exact tests for log-linear models.*exactRankTests*Computes exact p-values and quantiles using an implementation of theStreitberg/Roehmel shift algorithm.*fastICA*Implementation of FastICA algorithm to perform Independent ComponentAnalysis (ICA) and Projection Pursuit.*fdim*Functions for calculating fractal dimension.*fields*A collection of programs for curve and function fitting with anemphasis on spatial data. The major methods implemented include cubicand thin plate splines, universal Kriging and Kriging for large datasets. The main feature is that any covariance function implemented inR can be used for spatial prediction.*flexmix*Flexible Mixture Modeling: a general framework for finite mixtures ofregression models using the EM algorithm.*foreign*Functions for reading and writing data stored by statistical softwarelike Minitab, SAS, SPSS, Stata, etc. _Recommended_.*forward*Forward search approach to robust analysis in linear and generalizedlinear regression models.*fpc*Fixed point clusters, clusterwise regression and discriminant plots.*fracdiff*Maximum likelihood estimation of the parameters of a fractionallydifferenced ARIMA(p,d,q) model (Haslett and Raftery, AppliedStatistics, 1989).*ftnonpar*Features and strings for nonparametric regression.*g.data*Create and maintain delayed-data packages (DDP's).*gafit*Genetic algorithm for curve fitting.*gbm*Generalized Boosted Regression Models: implements extensions to Freundand Schapire's AdaBoost algorithm and J. Friedman's gradient boostingmachine. Includes regression methods for least squares, absolute loss,logistic, Poisson, Cox proportional hazards partial likelihood, andAdaBoost exponential loss.*gee*An implementation of the Liang/Zeger generalized estimating equationapproach to GLMs for dependent data.*geepack*Generalized estimating equations solver for parameters in mean, scale,and correlation structures, through mean link, scale link, andcorrelation link. Can also handle clustered categorical responses.*genetics*Classes and methods for handling genetic data. Includes classes torepresent genotypes and haplotypes at single markers up to multiplemarkers on multiple chromosomes, and functions for allele frequencies,flagging homo/heterozygotes, flagging carriers of certain alleles,computing disequlibrium, testing Hardy-Weinberg equilibrium, ...*geoR*Functions to perform geostatistical data analysis including model-basedmethods.*geoRglm*Functions for inference in generalised linear spatial models.*ggm*Functions for defining directed acyclic graphs and undirected graphs,finding induced graphs and fitting Gaussian Markov models.*gld*Basic functions for the generalised (Tukey) lambda distribution.*glmmML*A Maximum Likelihood approach to generalized linear models with randomintercept.*gpclib*General polygon clipping routines for R based on Alan Murta's Clibrary.*grasper*Generalized Regression Analysis and Spatial Predictions for R.*gregmisc*Miscellaneous functions written/maintained by Gregory R. Warnes.*gridBase*Integration of base and grid graphics.*gss*A comprehensive package for structural multivariate function estimationusing smoothing splines.*gstat*multivariable geostatistical modelling, prediction and simulation.Includes code for variogram modelling; simple, ordinary and universalpoint or block (co)kriging, sequential Gaussian or indicator(co)simulation, and map plotting functions.*gtkDevice*GTK graphics device driver that may be used independently of theR-GNOME interface and can be used to create R devices as embeddedcomponents in a GUI using a Gtk drawing area widget, e.g., using RGtk.*haplo.score*Score tests for association of traits with haplotypes when linkagephase is ambiguous.*hdf5*Interface to the NCSA HDF5 library.*hier.part*Hierarchical Partitioning: variance partition of a multivariate dataset.*homals*Homogeneity Analysis (HOMALS) package with optional Tcl/Tk interface.*hwde*Models and tests for departure from Hardy-Weinberg equilibrium andindependence between loci.*ifs*Iterated Function Systems distribution function estimator.*ineq*Inequality, concentration and poverty measures, and Lorenz curves(empirical and theoretic).*ipred*Improved predictive models by direct and indirect bootstrap aggregationin classification and regression as well as resampling based estimatorsof prediction error.*ismev*Functions to support the computations carried out in "An Introductionto Statistical Modeling of Extreme Values;' by S. Coles, 2001,Springer. The functions may be divided into the following groups;maxima/minima, order statistics, peaks over thresholds and pointprocesses.*its*An S4 class for handling irregular time series.*knnTree*Construct or predict with k-nearest-neighbor classifiers, usingcross-validation to select k, choose variables (by forward orbackwards selection), and choose scaling (from among no scaling,scaling each column by its SD, or scaling each column by its MAD).The finished classifier will consist of a classification tree with onesuch k-nn classifier in each leaf.*lars*Least Angle Regression, Lasso and Forward Stagewise: efficientprocedures for fitting an entire lasso sequence with the cost of asingle least squares fit.*lasso2*Routines and documentation for solving regression problems whileimposing an L1 constraint on the estimates, based on the algorithm ofOsborne et al. (1998)*lattice*Lattice graphics, an implementation of Trellis Graphics functions._Recommended_.*leaps*A package which performs an exhaustive search for the best subsets of agiven set of potential regressors, using a branch-and-bound algorithm,and also performs searches using a number of less time-consumingtechniques.*lgtdl*A set of methods for longitudinal data objects.*linprog*Solve linear programming/linear optimization problems by using thesimplex algorithm.*lme4*Fit linear and generalized linear mixed-effects models.*lmeSplines*Fit smoothing spline terms in Gaussian linear and nonlinearmixed-effects models.*lmtest*A collection of tests on the assumptions of linear regression modelsfrom the book "The linear regression model under test" by W. Kraemerand H. Sonnberger, 1986, Physica.*locfit*Local Regression, likelihood and density estimation.*logistf*Firth's bias reduced logistic regression approach with penalizedprofile likelihood based confidence intervals for parameter estimates.*logspline*Logspline density estimation.*lokern*Kernel regression smoothing with adaptive local or global plug-inbandwidth selection.*lpSolve*Functions that solve general linear/integer problems, assignmentproblems, and transportation problems via interfacing Lp_solve.*lpridge*Local polynomial (ridge) regression.*mapdata*Supplement to package *maps*, providing the larger and/orhigher-resolution databases.*maps*Draw geographical maps. Projection code and larger maps are inseparate packages.*maptools*Set of tools for manipulating and reading geographic data, inparticular ESRI shapefiles.*maptree*Functions with example data for graphing and mapping models fromhierarchical clustering and classification and regression trees.*maxstat*Maximally selected rank and Gauss statistics with several p-valueapproximations.*mclust*Model-based cluster analysis: the 2002 version of MCLUST.*mclust1998*Model-based cluster analysis: the 1998 version of MCLUST.*mda*Code for mixture discriminant analysis (MDA), flexible discriminantanalysis (FDA), penalized discriminant analysis (PDA), multivariateadditive regression splines (MARS), adaptive back-fitting splines(BRUTO), and penalized regression.*merror*Accuracy and precision of measurements.*mgcv*Routines for GAMs and other genralized ridge regression problems withmultiple smoothing parameter selection by GCV or UBRE. _Recommended_.*mimR*An R interface to MIM for graphical modeling in R.*mix*Estimation/multiple imputation programs for mixed categorical andcontinuous data.*mlbench*A collection of artificial and real-world machine learning benchmarkproblems, including the Boston housing data.*mmlcr*Mixed-mode latent class regression (also known as mixed-mode mixturemodel regression or mixed-mode mixture regression models) which canhandle both longitudinal and one-time responses.*moc*Fits a variety of mixtures models for multivariate observations withuser-difined distributions and curves.*msm*Functions for fitting continuous-time Markov multi-state models tocategorical processes observed at arbitrary times, optionally withmisclassified responses, and covariates on transition ormisclassification rates.*muhaz*Hazard function estimation in survival analysis.*multcomp*Multiple comparison procedures for the one-way layout.*multidim*Multidimensional descriptive statistics: factorial methods andclassification.*multiv*Functions for hierarchical clustering, partitioning, bond energyalgorithm, Sammon mapping, PCA and correspondence analysis.*mvnmle*ML estimation for multivariate normal data with missing values.*mvnormtest*Generalization of the Shapiro-Wilk test for multivariate variables.*mvtnorm*Multivariate normal and t distributions.*ncomplete*Functions to perform the regression depth method (RDM) to binaryregression to approximate the minimum number of observations that canbe removed such that the reduced data set has complete separation.*negenes*Estimating the number of essential genes in a genome on the basis ofdata from a random transposon mutagenesis experiment, through the useof a Gibbs sampler.*netCDF*Read data from netCDF files.*nlme*Fit and compare Gaussian linear and nonlinear mixed-effects models._Recommended_.*nlmeODE*Combine the *nlme* and *odesolve* packages for mixed-effects modellingusing differential equations.*nlrq*Nonlinear quantile regression.*nnet*Software for single hidden layer perceptrons ("feed-forward neuralnetworks"), and for multinomial log-linear models. Contained in the`VR' bundle. _Recommended_.*norm*Analysis of multivariate normal datasets with missing values.*normalp*A collection of utilities for normal of order p distributions (GeneralError Distributions).*normix*One-dimensional normal mixture models classes, for, e.g., densityestimation or clustering algorithms research and teaching; providingthe widely used Marron-Wand densities.*nortest*Five omnibus tests for the composite hypothesis of normality.*noverlap*Functions to perform the regression depth method (RDM) to binaryregression to approximate the amount of overlap, i.e., the minimalnumber of observations that need to be removed such that the reduceddata set has no longer overlap.*npmc*Nonparametric Multiple Comparisons: provides simultaneous rank testprocedures for the one-way layout without presuming a certaindistribution.*nprq*Nonparametric and sparse quantile regression methods.*odesolve*An interface for the Ordinary Differential Equation (ODE) solver lsoda.ODEs are expressed as R functions.*orientlib*Representations, conversions and display of orientation SO(3) data.*oz*Functions for plotting Australia's coastline and state boundaries.*pamr*Pam: Prediction Analysis for Microarrays.*panel*Functions and datasets for fitting models to Panel data.*pastecs*Package for Analysis of Space-Time Ecological Series.*pcurve*Fits a principal curve to a numeric multivariate dataset in arbitrarydimensions. Produces diagnostic plots. Also calculates Bray-Curtisand other distance matrices and performs multi-dimensional scaling andprincipal component analyses.*pear*Periodic Autoregression Analysis.*permax*Functions intended to facilitate certain basic analyses of DNA arraydata, especially with regard to comparing expression levels between twotypes of tissue.*pinktoe*Converts S trees to HTML/Perl files for interactive tree traversal.*pixmap*Functions for import, export, plotting and other manipulations ofbitmapped images.*pls.pcr*Multivariate regression by PLS and PCR.*polspline*Routines for the polynomial spline fitting routines hazard regression,hazard estimation with flexible tails, logspline, lspec, polyclass, andpolymars, by C. Kooperberg and co-authors.*polynom*A collection of functions to implement a class for univariatepolynomial manipulations.*pps*Functions to select samples using PPS (probability proportional tosize) sampling, for stratified simple random sampling, and to computejoint inclusion probabilities for Sampford's method of PPS sampling.*prabclus*Distance based parametric bootstrap tests for clustering, mainlythought for presence-absence data (clustering of species distributionmaps). Jaccard and Kulczynski distance measures, clustering of MDSscores, and nearest neighbor based noise detection.*princurve*Fits a principal curve to a matrix of points in arbitrary dimension.*pspline*Smoothing splines with penalties on order m derivatives.*psy*Various procedures used in psychometry: Kappa, ICC, Cronbach alpha,screeplot, PCA and related methods.*qtl*Analysis of experimental crosses to identify QTLs.*quadprog*For solving quadratic programming problems.*quantreg*Quantile regression and related methods.*qvcalc*Functions to compute quasi-variances and associated measures ofapproximation error.*randomForest*Breiman's random forest classifier.*relimp*Functions to facilitate inference on the relative importance ofpredictors in a linear or generalized linear model.*rgenoud*R version of GENetic Optimization Using Derivatives.*rimage*Functions for image processing, including Sobel filter, rank filters,fft, histogram equalization, and reading JPEG files.*rmeta*Functions for simple fixed and random effects meta-analysis fortwo-sample comparison of binary outcomes.*rpart*Recursive PARTitioning and regression trees. _Recommended_.*rpvm*R interface to PVM (Parallel Virtual Machine). Provides interface toPVM APIs, and examples and documentation for its use.*rqmcmb2*Markov chain marginal bootstrap for quantile regression.*rsprng*Provides interface to SPRNG (Scalable Parallel Random NumberGenerators) APIs, and examples and documentation for its use.*sampfling*Implements a modified version of the Sampford sampling algorithm.Given a quantity assigned to each unit in the population, samples aredrawn with probability proportional to te product of the quantities ofthe units included in the sample.*sca*Simple Component Analysis.*scatterplot3d*Plots a three dimensional (3D) point cloud perspectively.*seacarb*Calculates parameters of the seawater carbonate system.*seao*Simple Evolutionary Algorithm Optimization.*seao.gui*Simple Evolutionary Algorithm Optimization: graphical user interface.*segmented*Functions to estimate break-points of segmented relationships inregression models (GLMs).*sem*Functions for fitting general linear Structural Equation Models (withobserved and unobserved variables) by the method of maximum likelihoodusing the RAM approach.*serialize*Simple interfce for serializing to connections.*session*Functions for interacting with, saving and restoring R sessions.*sgeostat*An object-oriented framework for geostatistical modeling.*shapefiles*Functions to read and write ESRI shapefiles.*shapes*Routines for the statistical analysis of shapes, including procrustesanalysis, displaying shapes and principal components, testing for meanshape difference, thin-plate spline transformation grids and edgesuperimposition methods.*simpleboot*Simple bootstrap routines.*sm*Software linked to the book "Applied Smoothing Techniques for DataAnalysis: The Kernel Approach with S-PLUS Illustrations" by A. W.Bowman and A. Azzalini (1997), Oxford University Press.*sma*Functions for exploratory (statistical) microarray analysis.*smoothSurv*Survival regression with smoothed error distribution.*sn*Functions for manipulating skew-normal probability distributions andfor fitting them to data, in the scalar and the multivariate case.*sna*A range of tools for social network analysis, including node andgraph-level indices, structural distance and covariance methods,structural equivalence detection, p* modeling, and networkvisualization.*snow*Simple Network of Workstations: support for simple parallel computingin R.*som*Self-Organizing Maps (with application in gene clustering).*sound*A sound interface for R: Basic functions for dealing with `.wav' filesand sound samples.*spatial*Functions for kriging and point pattern analysis from "Modern AppliedStatistics with S" by W. Venables and B. Ripley. Contained in the`VR' bundle. _Recommended_.*spatstat*Data analysis and modelling of two-dimensional point patterns,including multitype points and spatial covariates.*spdep*A collection of functions to create spatial weights matrix objects frompolygon contiguities, from point patterns by distance and tesselations,for summarising these objects, and for permitting their use in spatialdata analysis; a collection of tests for spatial autocorrelation,including global Moran's I and Geary's C, local Moran's I, saddlepointapproximations for global and local Moran's I; and functions forestimating spatial simultaneous autoregressive (SAR) models. (Wasformerly the three packages: *spweights*, *sptests*, and *spsarlm*.)*splancs*Spatial and space-time point pattern analysis functions.*statmod*Miscellaneous biostatistical modelling functions.*strucchange*Various tests on structural change in linear regression models.*subselect*A collection of functions which assess the quality of variable subsetsas surrogates for a full data set, and search for subsets which areoptimal under various criteria.*survey*Summary statistics, generalized linear models, and general maximumlikelihood estimation for stratified, cluster-sampled, unequallyweighted survey samples.*survival*Functions for survival analysis, including penalised likelihood._Recommended_.*survrec*Survival analysis for recurrent event data.*systemfit*Contains functions for fitting simultaneous systems of equations usingOrdinary Least Sqaures (OLS), Two-Stage Least Squares (2SLS), andThree-Stage Least Squares (3SLS).*tapiR*Tools for accessing (UK) parliamentary information in R.*tensor*Tensor product of arrays.*tkrplot*Simple mechanism for placing R graphics in a Tk widget.*tree*Classification and regression trees.*tripack*A constrained two-dimensional Delaunay triangulation package.*tseries*Package for time series analysis with emphasis on non-linear modelling.*udunits*Interface to Unidata's routines to convert units.*vardiag*Interactive variogram diagnostics.*vcd*Functions and data sets based on the book "Visualizing CategoricalData" by Michael Friendly.*vegan*Various help functions for vegetation scientists and communityecologists.*waveslim*Basic wavelet routines for time series analysis.*wavethresh*Software to perform 1-d and 2-d wavelet statistics and transforms.*wle*Robust statistical inference via a weighted likelihood approach.*xgobi*Interface to the XGobi and XGvis programs for graphical data analysis.*xtable*Export data to LaTeX and HTML tables.See CRAN `src/contrib/PACKAGES' for more information.There is also a CRAN `src/contrib/Devel' directory which containspackages still "under development" or depending on features only present inthe current development versions of R. Volunteers are invited to givethese a try, of course. This area of CRAN currently contains*Dopt*Finding D-optimal experimental designs.*EMV*Estimation of missing values in a matrix by a k-th nearest neighboorsalgorithm.*GLMMGibbs*Generalised Linear Mixed Models by Gibbs sampling.*RPgSQL*Provides methods for accessing data stored in PostgreSQL tables.*Rmpi*An interface (wrapper) to MPI (Message-Passing Interface) APIs. Italso provides interactive R slave functionalities to make MPIprogramming easier in R than in C(++) or FORTRAN.*dseplus*Extensions to *dse*, the Dynamic Systems Estimation multivariate timeseries package. Contains PADI, juice and monitoring extensions.*ensemble*Ensembles of tree classifiers.*gllm*Routines for log-linear models of incomplete contingency tables,including some latent class models via EM and Fisher scoringapproaches.*meanscore*Mean Score method for missing covariate data in logistic regressionmodels.*runStat*Running median and mean.*twostage*Functions for optimal design of two-stage-studies using the Mean Scoremethod.*write.snns*Function for writing a SNNS pattern file from a data frame or matrix.5.1.3 Add-on packages from Omegahat-----------------------------------The `src/contrib/Omegahat' Directory of a CRAN site contains yet unreleasedpackages from the Omegahat Project for Statistical Computing(http://www.omegahat.org/). Currently, there are*CORBA*Dynamic CORBA client/server facilities for R. Connects to otherCORBA-aware applications developed in arbitrary languages, on differentmachines and allows R functionality to be exported in the same way toother applications.*OOP*OOP style classes and methods for R and S-PLUS. Object references andclass-based method definition are supported in the style of languagessuch as Java and C++.*REmbeddedPostgres*Allows R functions and objects to be used to implement SQL functions --per-record, aggregate and trigger functions.*REventLoop*An abstract event loop mechanism that is toolkit independent and can beused to to replace the R event loop.*RGdkPixbuf*S language functions to access the facilities in the GdkPixbuf libraryfor manipulating images.*RGnumeric*A plugin for the Gnumeric spreadsheet that allows R functions to becalled from cells within the sheet, automatic recalculation, etc.*RGtk*Facilities in the S language for programming graphical interfaces usingGtk, the Gnome GUI toolkit.*RGtkBindingGenerator*A meta-package which generates C and R code to provide bindings to aGtk-based library.*RGtkExtra*A collection of S functions that provide an interface to the widgets inthe gtk+extra library such as the GtkSheet data-grid display, iconlist, file list and directory tree.*RGtkGlade*S language bindings providing an interface to Glade, the interactiveGnome GUI creator.*RGtkHTML*A collection of S functions that provide an interface to creating andcontrolling an HTML widget which can be used to display HTML documentsfrom files or content generated dynamically in S.*RGtkViewers*A collection of tools for viewing different S objects, databases, classand widget hierarchies, S source file contents, etc.*RJavaDevice*A graphics device for R that uses Java components and graphics. APIs.*RObjectTables*The C and S code allows one to define R objects to be used as elementsof the search path with their own semantics and facilities for readingand writing variables. The objects implement a simple interface via Rfunctions (either methods or closures) and can access external data,e.g., in other applications, languages, formats, ...*RSMethods*An implementation of S version 4 methods and classes for R, consistentwith the basic material in "Programming with Data" by John M.Chambers, 1998, Springer NY.*RSPerl*An interface from R to an embedded, persistent Perl interpreter,allowing one to call arbitrary Perl subroutines, classes and methods.*RSPython*Allows Python programs to invoke S functions, methods, etc., and S codeto call Python functionality.*RXLisp*An interface to call XLisp-Stat functions from within R.*SASXML*Example for reading XML files in SAS 8.2 manner.*SJava*An interface from R to Java to create and call Java objects andmethods.*SLanguage*Functions and C support utilities to support S language programmingthat can work in both R and S-PLUS.*SNetscape*Plugin for Netscape and JavaScript.*SWinRegistry*Provides access from within R to read and write the Windows registry.*SWinTypeLibs*Provides ways to extract type information from type libraries and/orDCOM objects that describes the methods, properties, etc. of aninterface.*SXalan*Process XML documents using XSL functions implemented in R anddynamically substituting output from R.*Slcc*Parses C source code, allowing one to analyze and automaticallygenerate interfaces from S to that code, including the table ofS-accessible native symbols, parameter count and type information, Sconstructors from C objects, call graphs, etc.*Sxslt*An extension module for libxslt, the XML-XSL document translator, thatallows XSL functions to be implemented via R functions.5.1.4 Add-on packages from BioConductor---------------------------------------The Bioconductor Project (http://www.bioconductor.org) produces an opensource software framework that will assist biologists and statisticiansworking in bioinformatics, with primary emphasis on inference using DNAmicroarrays. The following R packages are contained in the current releaseof BioConductor, with more packages under development.*AnnBuilder*Assemble and process genomic annotation data, from databases such asGenBank, the Gene Ontology Consortium, LocusLink, UniGene, the UCSCHuman Genome Project.*Biobase*Object-oriented representation and manipulation of genomic data (S4class structure).*DynDoc*Functionality to create and interact with dynamic documents, vignettes,and other navigable documents.*RBGL*An interface between the graph package and the Boost graph libraries,allowing for fast manipulation of graph objects in R.*ROC*Receiver Operating Characteristic (ROC) approach for identifying genesthat are differentially expressed in two types of samples.*Rgraphviz*An interface with Graphviz for plotting graph objects in R.*Ruuid*Creates Universally Unique ID values (UUIDs) in R.*SAGElyzer*Locates genes based on SAGE tags.*affy*Methods for Affymetrix Oligonucleotide Arrays.*affycomp*Graphics toolbox for assessment of Affymetrix expression measures.*affydata*Affymetrix data for demonstration purposes.*annotate*Associate experimental data in real time to biological metadata fromweb databases such as GenBank, LocusLink and PubMed. Process and storequery results. Generate HTML reports of analyses.*edd*Expression density diagnostics: graphical methods and patternrecognition algorithms for distribution shape classification.*genefilter*Tools for sequentially filtering genes using a wide variety offiltering functions. Example of filters include: number of missingvalue, coefficient of variation of expression measures, ANOVA p-value,Cox model p-values. Sequential application of filtering functions togenes.*geneplotter*Graphical tools for genomic data, for example for plotting expressiondata along a chromosome or producing color images of expression datamatrices.*graph*Classes and tools for creating and manipulating graphs within R.*hexbin*Binning functions, in particular hexagonal bins for graphing.*limma*Linear models for microarray data.*marrayClasses*Class definitions for pre-normalized and normalized cDNA microarraydata. Basic methods for accessing/replacing, printing, and subsetting.*marrayInput*Functions for reading microarray data into R from different imageanalysis output files, and probe and target description files. Widgetsare supplied to facilitate and automate data input and the creation ofmicroarray specific R objects for storing these data.*marrayNorm*Functions for location and scale normalization procedures based onrobust local regression.*marrayPlots*Functions for diagnostic plots for pre- and post-normalization cDNAmicroarray intensity data: boxplots, scatter-plots, color images.*marrayTools*Miscellaneous functions used in the functional genomics core facilityin UCB and UCSF.*multtest*Multiple testing procedures for controlling the family-wise error rate(FWER) and the false discovery rate (FDR). Tests can be based on t-or F-statistics for one- and two-factor designs, and permutationprocedures are available to estimate adjusted p-values.*reposTools*Tools for dealing with file repositories and allow users to easilyinstall, update, and distribute packages, vignettes, and other files.*rhdf5*Storage and retrieval of large datasets using the HDF5 library and fileformat.*tkWidgets*Widgets in Tcl/Tk that provide functionality for Bioconductor packages.*vsn*Calibration and variance stabilizing transformations for bothAffymetrix and cDNA array data.*widgetTools*Tools for creating Tcl/Tk widgets, i.e., small-scale graphical userinterfaces.These packages will eventually also be made available via CRAN as well.5.1.5 Other add-on packages---------------------------Jim Lindsey <jlindsey@luc.ac.be> has written a collection of R packages fornonlinear regression and repeated measurements, consisting of *event*(event history procedures and models), *gnlm* (generalized nonlinearregression models), *growth* (multivariate normal andelliptically-contoured repeated measurements models), *repeated*(non-normal repeated measurements models), *rmutil* (utilities fornonlinear regression and repeated measurements), and *stable* (probabilityfunctions and generalized regression models for stable distributions). Allanalyses in the new edition of his book "Models for Repeated Measurements"(1999, Oxford University Press) were carried out using these packages. Jimhas also started *dna*, a package with procedures for the analysis of DNAsequences. Jim's packages can be obtained from`http://www.luc.ac.be/~jlindsey/rcode.html'.More code has been posted to the R-help mailing list, and can beobtained from the mailing list archive.5.2 How can add-on packages be installed?=========================================(Unix only.) The add-on packages on CRAN come as gzipped tar files named`PKG_VERSION.tar.gz', which may in fact be "bundles" containing more thanone package. Provided that `tar' and `gzip' are available on your system,type$ R CMD INSTALL /path/to/PKG_VERSION.tar.gzat the shell prompt to install to the library tree rooted at the firstdirectory given in `R_LIBS' (see below) if this is set and non-null, and tothe default library (the `library' subdirectory of ``R_HOME'') otherwise.(Versions of R prior to 1.3.0 installed to the default library by default.)To install to another tree (e.g., your private one), use$ R CMD INSTALL -l LIB /path/to/PKG_VERSION.tar.gzwhere LIB gives the path to the library tree to install to.Even more conveniently, you can install and automatically updatepackages from within R if you have access to CRAN. See the help page for`CRAN.packages()' for more information.You can use several library trees of add-on packages. The easiest wayto tell R to use these is via the environment variable `R_LIBS' whichshould be a colon-separated list of directories at which R library treesare rooted. You do not have to specify the default tree in `R_LIBS'.E.g., to use a private tree in `$HOME/lib/R' and a public site-wide tree in`/usr/local/lib/R-contrib', putR_LIBS="$HOME/lib/R:/usr/local/lib/R-contrib"; export R_LIBSinto your (Bourne) shell profile or even preferably, add the lineR_LIBS="$HOME/lib/R:/usr/local/lib/R-contrib"your `~/.Renviron' file. (Note that no `export' statement is needed orallowed in this file; see the on-line help for `Startup' for moreinformation.)5.3 How can add-on packages be used?====================================To find out which additional packages are available on your system, typelibrary()at the R prompt.This produces something likePackages in `/home/me/lib/R':mystuff My own R functions, nicely packaged but not documentedPackages in `/usr/local/lib/R/library':KernSmooth Functions for kernel smoothing for Wand & Jones (1995)MASS Main Library of Venables and Ripley's MASSbase The R base packageboot Bootstrap R (S-Plus) Functions (Canty)class Functions for classificationcluster Functions for clustering (by Rousseeuw et al.)ctest Classical Testseda Exploratory Data Analysisforeign Read data stored by Minitab, S, SAS, SPSS, Stata, ...grid The Grid Graphics Packagelattice Lattice Graphicslqs Resistant Regression and Covariance Estimationmethods Formal Methods and Classesmle Maximum likelihood estimationmgcv Multiple smoothing parameter estimation and GAMs by GCVmodreg Modern Regression: Smoothing and Local Methodsmva Classical Multivariate Analysisnlme Linear and nonlinear mixed effects modelsnls Nonlinear regressionnnet Feed-forward neural networks and multinomial log-linearmodelsrpart Recursive partitioningspatial functions for kriging and point pattern analysissplines Regression Spline Functions and Classesstepfun Step Functions, including Empirical Distributionssurvival Survival analysis, including penalised likelihoodtcltk Tcl/Tk Interfacetools Tools for Package Development and Administrationts Time series functionsYou can "load" the installed package PKG bylibrary(PKG)You can then find out which functions it provides by typing one oflibrary(help = PKG)help(package = PKG)You can unload the loaded package PKG bydetach("package:PKG")5.4 How can add-on packages be removed?=======================================Use$ R CMD REMOVE PKG_1 ... PKG_Nto remove the packages PKG_1, ..., PKG_N from the library tree rooted atthe first directory given in `R_LIBS' if this is set and non-null, and fromthe default library otherwise. (Versions of R prior to 1.3.0 removed fromthe default library by default.)To remove from library LIB, do$ R CMD REMOVE -l LIB PKG_1 ... PKG_N5.5 How can I create an R package?==================================A package consists of a subdirectory containing the files `DESCRIPTION' and`INDEX', and the subdirectories `R', `data', `demo', `exec', `inst', `man',`src', and `tests' (some of which can be missing). Optionally the packagecan also contain script files `configure' and `cleanup' which are executedbefore and after installation.See section "Creating R packages" in `Writing R Extensions', for details.This manual is included in the R distribution, *note What documentationexists for R?::, and gives information on package structure, the configureand cleanup mechanisms, and on automated package checking and building.R version 1.3.0 has added the function `package.skeleton()' which willset up directories, save data and code, and create skeleton help files fora set of R functions and datasets.*Note What is CRAN?::, for information on uploading a package to CRAN.5.6 How can I contribute to R?==============================R is in active development and there is always a risk of bugs creeping in.Also, the developers do not have access to all possible machines capable ofrunning R. So, simply using it and communicating problems is certainly ofgreat value.One place where functionality is still missing is the modeling softwareas described in "Statistical Models in S" (see *Note What is S?::);Generalized Additive Models (*note Are GAMs implemented in R?::) and someof the nonlinear modeling code are not there yet.The R Developer Page (http://developer.R-project.org/) acts as anintermediate repository for more or less finalized ideas and plans for theR statistical system. It contains (pointers to) TODO lists, RFCs, variousother writeups, ideas lists, and CVS miscellanea.Many (more) of the packages available at the Statlib S Repository mightbe worth porting to R.If you are interested in working on any of these projects, please notifyKurt Hornik <Kurt.Hornik@R-project.org>.6 R and Emacs*************6.1 Is there Emacs support for R?=================================There is an Emacs package called ESS ("Emacs Speaks Statistics") whichprovides a standard interface between statistical programs and statisticalprocesses. It is intended to provide assistance for interactivestatistical programming and data analysis. Languages supported include: Sdialects (S 3/4, S-PLUS 3.x/4.x/5.x, and R), LispStat dialects (XLispStat,ViSta) and SAS. Stata and SPSS dialect (SPSS, PSPP) support is beingexamined for possible future implementationESS grew out of the need for bug fixes and extensions to S-mode 4.8(which was a GNU Emacs interface to S/S-PLUS version 3 only). The currentset of developers desired support for XEmacs, R, S4, and MS Windows. Inaddition, with new modes being developed for R, Stata, and SAS, it was feltthat a unifying interface and framework for the user interface wouldbenefit both the user and the developer, by helping both groups conform tostandard Emacs usage. The end result is an increase in efficiency forstatistical programming and data analysis, over the usual tools.R support contains code for editing R source code (syntactic indentationand highlighting of source code, partial evaluations of code, loading anderror-checking of code, and source code revision maintenance) anddocumentation (syntactic indentation and highlighting of source code,sending examples to running ESS process, and previewing), interacting withan inferior R process from within Emacs (command-line editing, searchablecommand history, command-line completion of R object and file names, quickaccess to object and search lists, transcript recording, and an interfaceto the help system), and transcript manipulation (recording and savingtranscript files, manipulating and editing saved transcripts, andre-evaluating commands from transcript files).The latest stable version of ESS are available via CRAN or the ESS webpage (http://ESS.R-project.org/). The HTML version of the documentationcan be found at `http://stat.ethz.ch/ESS/'.ESS comes with detailed installation instructions.For help with ESS, send email to <ESS-help@stat.ethz.ch>.Please send bug reports and suggestions on ESS to<ESS-bugs@stat.math.ethz.ch>. The easiest way to do this from is withinEmacs by typing `M-x ess-submit-bug-report' or using the [ESS] or [iESS]pulldown menus.6.2 Should I run R from within Emacs?=====================================Yes, _definitely_. Inferior R mode provides a readline/history mechanism,object name completion, and syntax-based highlighting of the interactionbuffer using Font Lock mode, as well as a very convenient interface to theR help system.Of course, it also integrates nicely with the mechanisms for editing Rsource using Emacs. One can write code in one Emacs buffer and send wholeor parts of it for execution to R; this is helpful for both data analysisand programming. One can also seamlessly integrate with a revision controlsystem, in order to maintain a log of changes in your programs and data, aswell as to allow for the retrieval of past versions of the code.In addition, it allows you to keep a record of your session, which canalso be used for error recovery through the use of the transcript mode.To specify command line arguments for the inferior R process, use `C-uM-x R' for starting R.6.3 Debugging R from within Emacs=================================To debug R "from within Emacs", there are several possibilities. To usethe Emacs GUD (Grand Unified Debugger) library with the recommendeddebugger GDB, type `M-x gdb' and give the path to the R _binary_ asargument. At the `gdb' prompt, set `R_HOME' and other environmentvariables as needed (using e.g. `set env R_HOME /path/to/R/', but see alsobelow), and start the binary with the desired arguments (e.g., `run--quiet').If you have ESS, you can do `C-u M-x R <RET> - d <SPC> g d b <RET>' tostart an inferior R process with arguments `-d gdb'.A third option is to start an inferior R process via ESS (`M-x R') andthen start GUD (`M-x gdb') giving the R binary (using its full path name)as the program to debug. Use the program `ps' to find the process numberof the currently running R process then use the `attach' command in gdb toattach it to that process. One advantage of this method is that you haveseparate `*R*' and `*gud-gdb*' windows. Within the `*R*' window you haveall the ESS facilities, such as object-name completion, that we know andlove.When using GUD mode for debugging from within Emacs, you may find itmost convenient to use the directory with your code in it as the currentworking directory and then make a symbolic link from that directory to theR binary. That way `.gdbinit' can stay in the directory with the code andbe used to set up the environment and the search paths for the source, e.g.as follows:set env R_HOME /opt/Rset env R_PAPERSIZE letterset env R_PRINTCMD lprdir /opt/R/src/appldir /opt/R/src/maindir /opt/R/src/nmathdir /opt/R/src/unix7 R Miscellanea***************7.1 Why does R run out of memory?=================================Versions of R prior to 1.2.0 used a _static_ memory model. At startup, Rasked the operating system to reserve a fixed amount of memory for it. Thesize of this chunk could not be changed subsequently. Hence, it couldhappen that not enough memory was allocated, e.g., when trying to readlarge data sets into R. In such cases, it was necessary to restart R withmore memory available, as controlled by the command line options `--nsize'and `--vsize'.R version 1.2.0 introduces a new "generational" garbage collector, whichwill increase the memory available to R as needed. Hence, userintervention is no longer necessary for ensuring that enough memory isavailable.The new garbage collector does not move objects in memory, meaning thatit is possible for the free memory to become fragmented so that largeobjects cannot be allocated even when there is apparently enough memory forthem.7.2 Why does sourcing a correct file fail?==========================================Versions of R prior to 1.2.1 may have had problems parsing files not endingin a newline. Earlier R versions had a similar problem when reading indata files. This should no longer happen.7.3 How can I set components of a list to NULL?===============================================You can usex[i] <- list(NULL)to set component `i' of the list `x' to `NULL', similarly for namedcomponents. Do not set `x[i]' or `x[[i]]' to `NULL', because this willremove the corresponding component from the list.For dropping the row names of a matrix `x', it may be easier to use`rownames(x) <- NULL', similarly for column names.7.4 How can I save my workspace?================================`save.image()' saves the objects in the user's `.GlobalEnv' to the file`.RData' in the R startup directory. (This is also what happens after`q("yes")'.) Using `save.image(FILE)' one can save the image under adifferent name.7.5 How can I clean up my workspace?====================================To remove all objects in the currently active environment (typically`.GlobalEnv'), you can dorm(list = ls(all = TRUE))(Without `all = TRUE', only the objects with names not starting with a `.'are removed.)7.6 How can I get eval() and D() to work?=========================================Strange things will happen if you use `eval(print(x), envir = e)' or`D(x^2, "x")'. The first one will either tell you that "`x'" is not found,or print the value of the wrong `x'. The other one will likely return zeroif `x' exists, and an error otherwise.This is because in both cases, the first argument is evaluated in thecalling environment first. The result (which should be an object of mode`"expression"' or `"call"') is then evaluated or differentiated. What you(most likely) really want is obtained by "quoting" the first argument uponsurrounding it with `expression()'. For example,R> D(expression(x^2), "x")2 * xAlthough this behavior may initially seem to be rather strange, isperfectly logical. The "intuitive" behavior could easily be implemented,but problems would arise whenever the expression is contained in avariable, passed as a parameter, or is the result of a function call.Consider for instance the semantics in cases likeD2 <- function(e, n) D(D(e, n), n)org <- function(y) eval(substitute(y), sys.frame(sys.parent(n = 2)))g(a * b)See the help page for `deriv()' for more examples.7.7 Why do my matrices lose dimensions?=======================================When a matrix with a single row or column is created by a subscriptingoperation, e.g., `row <- mat[2, ]', it is by default turned into a vector.In a similar way if an array with dimension, say, 2 x 3 x 1 x 4 is createdby subscripting it will be coerced into a 2 x 3 x 4 array, losing theunnecessary dimension. After much discussion this has been determined tobe a _feature_.To prevent this happening, add the option `drop = FALSE' to thesubscripting. For example,rowmatrix <- mat[2, , drop = FALSE] # creates a row matrixcolmatrix <- mat[, 2, drop = FALSE] # creates a column matrixa <- b[1, 1, 1, drop = FALSE] # creates a 1 x 1 x 1 arrayThe `drop = FALSE' option should be used defensively when programming.For example, the statementsomerows <- mat[index, ]will return a vector rather than a matrix if `index' happens to have length1, causing errors later in the code. It should probably be rewritten assomerows <- mat[index, , drop = FALSE]7.8 How does autoloading work?==============================R has a special environment called `.AutoloadEnv'. Using `autoload(NAME,PKG)', where NAME and PKG are strings giving the names of an object and thepackage containing it, stores some information in this environment. When Rtries to evaluate NAME, it loads the corresponding package PKG andreevaluates NAME in the new package's environment.Using this mechanism makes R behave as if the package was loaded, butdoes not occupy memory (yet).See the help page for `autoload()' for a very nice example.7.9 How should I set options?=============================The function `options()' allows setting and examining a variety of global"options" which affect the way in which R computes and displays itsresults. The variable `.Options' holds the current values of theseoptions, but should never directly be assigned to unless you want to driveyourself crazy--simply pretend that it is a "read-only" variable.For example, giventest1 <- function(x = pi, dig = 3) {oo <- options(digits = dig); on.exit(options(oo));cat(.Options$digits, x, "\n")}test2 <- function(x = pi, dig = 3) {.Options$digits <- digcat(.Options$digits, x, "\n")}we obtain:R> test1()3 3.14R> test2()3 3.141593What is really used is the _global_ value of `.Options', and using`options(OPT = VAL)' correctly updates it. Local copies of `.Options',either in `.GlobalEnv' or in a function environment (frame), are justsilently disregarded.7.10 How do file names work in Windows?=======================================As R uses C-style string handling, `\' is treated as an escape character,so that for example one can enter a newline as `\n'. When you really needa `\', you have to escape it with another `\'.Thus, in filenames use something like `"c:\\data\\money.dat"'. You canalso replace `\' by `/' (`"c:/data/money.dat"').7.11 Why does plotting give a color allocation error?=====================================================Sometimes plotting, e.g., when running `demo("image")', results in "Error:color allocation error". This is an X problem, and only indirectly relatedto R. It occurs when applications started prior to R have used all theavailable colors. (How many colors are available depends on the Xconfiguration; sometimes only 256 colors can be used.)One application which is notorious for "eating" colors is Netscape. Ifthe problem occurs when Netscape is running, try (re)starting it witheither the `-no-install' (to use the default colormap) or the `-install'(to install a private colormap) option.You could also set the `colortype' of `X11()' to `"pseudo.cube"' ratherthan the default `"pseudo"'. See the help page for `X11()' for moreinformation.7.12 How do I convert factors to numeric?=========================================It may happen that when reading numeric data into R (usually, when readingin a file), they come in as factors. If `f' is such a factor object, youcan useas.numeric(as.character(f))to get the numbers back. More efficient, but harder to remember, isas.numeric(levels(f))[as.integer(f)]In any case, do not call `as.numeric()' or their likes directly for thetask at hand (as `as.numeric()' or `unclass()' give the internal codes).7.13 Are Trellis displays implemented in R?===========================================The recommended package *lattice* (which is based on another recommendedpackage, *grid*) provides graphical functionality that is compatible withmost Trellis commands.You could also look at `coplot()' and `dotchart()' which might do atleast some of what you want. Note also that the R version of `pairs()' isfairly general and provides most of the functionality of `splom()', andthat R's default plot method has an argument `asp' allowing to specify (andfix against device resizing) the aspect ratio of the plot.(Because the word "Trellis" has been claimed as a trademark we do notuse it in R. The name "lattice" has been chosen for the R equivalent.)7.14 What are the enclosing and parent environments?====================================================Inside a function you may want to access variables in two additionalenvironments: the one that the function was defined in ("enclosing"), andthe one it was invoked in ("parent").If you create a function at the command line or load it in a package itsenclosing environment is the global workspace. If you define a function`f()' inside another function `g()' its enclosing environment is theenvironment inside `g()'. The enclosing environment for a function isfixed when the function is created. You can find out the enclosingenvironment for a function `f()' using `environment(f)'.The "parent" environment, on the other hand, is defined when you invokea function. If you invoke `lm()' at the command line its parentenvironment is the global workspace, if you invoke it inside a function`f()' then its parent environment is the environment inside `f()'. You canfind out the parent environment for an invocation of a function by using`parent.frame()' or `sys.frame(sys.parent())'.So for most user-visible functions the enclosing environment will be theglobal workspace, since that is where most functions are defined. Theparent environment will be wherever the function happens to be called from.If a function `f()' is defined inside another function `g()' it willprobably be used inside `g()' as well, so its parent environment andenclosing environment will probably be the same.Parent environments are important because things like model formulasneed to be evaluated in the environment the function was called from, sincethat's where all the variables will be available. This relies on theparent environment being potentially different with each invocation.Enclosing environments are important because a function can usevariables in the enclosing environment to share information with otherfunctions or with other invocations of itself (see the section on lexicalscoping). This relies on the enclosing environment being the same eachtime the function is invoked.Scoping _is_ hard. Looking at examples helps. It is particularlyinstructive to look at examples that work differently in R and S and try tosee why they differ. One way to describe the scoping differences between Rand S is to say that in S the enclosing environment is _always_ the globalworkspace, but in R the enclosing environment is wherever the function wascreated.7.15 How can I substitute into a plot label?============================================Often, it is desired to use the value of an R object in a plot label, e.g.,a title. This is easily accomplished using `paste()' if the label is asimple character string, but not always obvious in case the label is anexpression (for refined mathematical annotation). In such a case, eitheruse `parse()' on your pasted character string or use `substitute()' on anexpression. For example, if `ahat' is an estimator of your parameter a ofinterest, usetitle(substitute(hat(a) == ahat, list(ahat = ahat)))(note that it is `==' and not `='). There are more worked examples in themailing list achives.7.16 What are valid names?==========================When creating data frames using `data.frame()' or `read.table()', R bydefault ensures that the variable names are syntactically valid. (Theargument `check.names' to these functions controls whether variable namesare checked and adjusted by `make.names()' if needed.)To understand what names are "valid", one needs to take into accountthat the term "name" is used in several different (but related) ways in thelanguage:1. A _syntactic name_ is a string the parser interprets as this type ofexpression. It consists of letters, numbers, and the dot characterand starts with a letter or the dot.2. An _object name_ is a string associated with an object that isassigned in an expression either by having the object name on the leftof an assignment operation or as an argument to the `assign()'function. It is usually a syntactic name as well, but can be anynon-empty string if it is quoted (and it is always quoted in the callto `assign()').3. An _argument name_ is what appears to the left of the equals sign whensupplying an argument in a function call (for example, `f(trim=.5)').Argument names are also usually syntactic names, but again can beanything if they are quoted.4. An _element name_ is a string that identifies a piece of an object (acomponent of a list, for example.) When it is used on the right ofthe `$' operator, it must be a syntactic name, or quoted. Otherwise,element names can be any strings. (When an object is used as adatabase, as in a call to `eval()' or `attach()', the element namesbecome object names.)5. Finally, a _file name_ is a string identifying a file in the operatingsystem for reading, writing, etc. It really has nothing much to dowith names in the language, but it is traditional to call thesestrings file "names".7.17 Are GAMs implemented in R?===============================There is a `gam()' function for Generalized Additive Models in package*mgcv*, but it is not an exact clone of what is described in the White Book(no `lo()' for example). Package *gss* can fit spline-based GAMs too. Andif you can accept regression splines you can use `glm()'. For gaussianGAMs you can use `bruto()' from package *mda*.7.18 Why is the output not printed when I source() a file?==========================================================Most R commands do not generate any output. The command1+1computes the value 2 and returns it; the commandsummary(glm(y~x+z, family=binomial))fits a logistic regression model, computes some summary information andreturns an object of class `"summary.glm"' (*note How should I writesummary methods?::).If you type `1+1' or `summary(glm(y~x+z, family=binomial))' at thecommand line the returned value is automatically printed (unless it is`invisible()'), but in other circumstances, such as in a `source()'d fileor inside a function it isn't printed unless you specifically print it.To print the value useprint(1+1)orprint(summary(glm(y~x+z, family=binomial)))instead, or use `source(FILE, echo=TRUE)'.7.19 Why does outer() behave strangely with my function?========================================================As the help for `outer()' indicates, it does not work on arbitraryfunctions the way the `apply()' family does. It requires functions thatare vectorized to work elementwise on arrays. As you can see by looking atthe code, `outer(x, y, FUN)' creates two large vectors containing everypossible combination of elements of `x' and `y' and then passes this to`FUN' all at once. Your function probably cannot handle two large vectorsas parameters.If you have a function that cannot handle two vectors but can handle twoscalars, then you can still use `outer()' but you will need to wrap yourfunction up first, to simulate vectorized behavior. Suppose your functionisfoo <- function(x, y, happy) {stopifnot(length(x) == 1, length(y) == 1) # scalars only!(x + y) * happy}If you define the general functionwrapper <- function(x, y, my.fun, ...) {sapply(seq(along = x), FUN = function(i) my.fun(x[i], y[i], ...))}then you can use `outer()' by writing, e.g.,outer(1:4, 1:2, FUN = wrapper, my.fun = foo, happy = 10)7.20 Why does the output from anova() depend on the order of factors in the model?==================================================================================In a model such as `~A+B+A:B', R will report the difference in sums ofsquares between the models `~1', `~A', `~A+B' and `~A+B+A:B'. If the modelwere `~B+A+A:B', R would report differences between `~1', `~B', `~A+B', and`~A+B+A:B' . In the first case the sum of squares for `A' is comparing `~1'and `~A', in the second case it is comparing `~B' and `~B+A'. In anon-orthogonal design (i.e., most unbalanced designs) these comparisons are(conceptually and numerically) different.Some packages report instead the sums of squares based on comparing thefull model to the models with each factor removed one at a time (the famous`Type III sums of squares' from SAS, for example). These do not depend onthe order of factors in the model. The question of which set of sums ofsquares is the Right Thing provokes low-level holy wars on R-help from timeto time.There is no need to be agitated about the particular sums of squaresthat R reports. You can compute your favorite sums of squares quiteeasily. Any two models can be compared with `anova(MODEL1, MODEL2)', and`drop1(MODEL1)' will show the sums of squares resulting from droppingsingle terms.7.21 How do I produce PNG graphics in batch mode?=================================================Under Unix, the `png()' device uses the X11 driver, which is a problem inbatch mode or for remote operation. If you have Ghostscript you can use`bitmap()', which produces a PostScript file then converts it to any bitmapformat supported by ghostscript. On some installations this produces uglyoutput, on others it is perfectly satisfactory. In theory one could alsouse Xvfb, which provides an X server with no display.7.22 How can I get command line editing to work?================================================The Unix command-line interface to R can only provide the inbuilt commandline editor which allows recall, editing and re-submission of priorcommands provided that the GNU readline library is available at the time Ris configured for compilation. Note that the `development' version ofreadline including the appropriate headers is needed: users of Linux binarydistributions will need to install packages such as `libreadline-dev'(Debian) or `readline-devel' (Red Hat).7.23 How can I turn a string into a variable?=============================================If you havevarname <- c("a", "b", "d")you can doget(varname[1]) + 2fora + 2orassign(varname[1], 2 + 2)fora <- 2 + 2oreval(substitute(lm(y ~ x + variable),list(variable = as.name(varname[1]))forlm(y ~ x + a)At least in the first two cases it is often easier to just use a list,and then you can easily index it by namevars <- list(a = 1:10, b = rnorm(100), d = LETTERS)vars[["a"]]without any of this messing about.7.24 Why do lattice/trellis graphics not work?==============================================The most likely reason is that you forgot to tell R to display the graph.Lattice functions such as `xyplot()' create a graph object, but do notdisplay it (the same is true of Trellis graphics in S-PLUS). The `print()'method for the graph object produces the actual display. When you usethese functions interactively at the command line, the result isautomatically printed, but in `source()' or inside your own functions youwill need an explicit `print()' statement.7.25 How can I sort the rows of a data frame?=============================================To sort the rows within a data frame, with respect to the values in one ormore of the columns, simply use `order()'.8 R Programming***************8.1 How should I write summary methods?=======================================Suppose you want to provide a summary method for class `"foo"'. Then`summary.foo()' should not print anything, but return an object of class`"summary.foo"', _and_ you should write a method `print.summary.foo()'which nicely prints the summary information and invisibly returns itsobject. This approach is preferred over having `summary.foo()' printsummary information and return something useful, as sometimes you need tograb something computed by `summary()' inside a function or similar. Insuch cases you don't want anything printed.8.2 How can I debug dynamically loaded code?============================================Roughly speaking, you need to start R inside the debugger, load the code,send an interrupt, and then set the required breakpoints.See section "Finding entry points in dynamically loaded code" in`Writing R Extensions'. This manual is included in the R distribution,*note What documentation exists for R?::.8.3 How can I inspect R objects when debugging?===============================================The most convenient way is to call `R_PV' from the symbolic debugger.See section "Inspecting R objects when debugging" in `Writing RExtensions'.8.4 How can I change compilation flags?=======================================Suppose you have C code file for dynloading into R, but you want to use `RCMD SHLIB' with compilation flags other than the default ones (which weredetermined when R was built). You could change the file``R_HOME'/etc/Makeconf' to reflect your preferences. If you are a Bourneshell user, you can also pass the desired flags to Make (which is used forcontrolling compilation) via the Make variable `MAKEFLAGS', as inMAKEFLAGS="CFLAGS=-O3" R CMD SHLIB *.c9 R Bugs********9.1 What is a bug?==================If R executes an illegal instruction, or dies with an operating systemerror message that indicates a problem in the program (as opposed tosomething like "disk full"), then it is certainly a bug. If you call`.C()', `.Fortran()', `.External()' or `.Call()' (or `.Internal()')yourself (or in a function you wrote), you can always crash R by usingwrong argument types (modes). This is not a bug.Taking forever to complete a command can be a bug, but you must makecertain that it was really R's fault. Some commands simply take a longtime. If the input was such that you _know_ it should have been processedquickly, report a bug. If you don't know whether the command should take along time, find out by looking in the manual or by asking for assistance.If a command you are familiar with causes an R error message in a casewhere its usual definition ought to be reasonable, it is probably a bug.If a command does the wrong thing, that is a bug. But be sure you know forcertain what it ought to have done. If you aren't familiar with thecommand, or don't know for certain how the command is supposed to work,then it might actually be working right. Rather than jumping toconclusions, show the problem to someone who knows for certain.Finally, a command's intended definition may not be best for statisticalanalysis. This is a very important sort of problem, but it is also amatter of judgment. Also, it is easy to come to such a conclusion out ofignorance of some of the existing features. It is probably best not tocomplain about such a problem until you have checked the documentation inthe usual ways, feel confident that you understand it, and know for certainthat what you want is not available. If you are not sure what the commandis supposed to do after a careful reading of the manual this indicates abug in the manual. The manual's job is to make everything clear. It isjust as important to report documentation bugs as program bugs. However,we know that the introductory documentation is seriously inadequate, so youdon't need to report this.If the online argument list of a function disagrees with the manual, oneof them must be wrong, so report the bug.9.2 How to report a bug=======================When you decide that there is a bug, it is important to report it and toreport it in a way which is useful. What is most useful is an exactdescription of what commands you type, starting with the shell command torun R, until the problem happens. Always include the version of R,machine, and operating system that you are using; type `version' in R toprint this.The most important principle in reporting a bug is to report _facts_,not hypotheses or categorizations. It is always easier to report thefacts, but people seem to prefer to strain to posit explanations and reportthem instead. If the explanations are based on guesses about how R isimplemented, they will be useless; others will have to try to figure outwhat the facts must have been to lead to such speculations. Sometimes thisis impossible. But in any case, it is unnecessary work for the ones tryingto fix the problem.For example, suppose that on a data set which you know to be quite largethe commandR> data.frame(x, y, z, monday, tuesday)never returns. Do not report that `data.frame()' fails for large datasets. Perhaps it fails when a variable name is a day of the week. If thisis so then when others got your report they would try out the`data.frame()' command on a large data set, probably with no day of theweek variable name, and not see any problem. There is no way in the worldthat others could guess that they should try a day of the week variablename.Or perhaps the command fails because the last command you used was amethod for `"["()' that had a bug causing R's internal data structures tobe corrupted and making the `data.frame()' command fail from then on. Thisis why others need to know what other commands you have typed (or read fromyour startup file).It is very useful to try and find simple examples that produceapparently the same bug, and somewhat useful to find simple examples thatmight be expected to produce the bug but actually do not. If you want todebug the problem and find exactly what caused it, that is wonderful. Youshould still report the facts as well as any explanations or solutions.Please include an example that reproduces the problem, preferably thesimplest one you have found.Invoking R with the `--vanilla' option may help in isolating a bug.This ensures that the site profile and saved data files are not read.On Unix systems a bug report can be generated using the function`bug.report()'. This automatically includes the version information andsends the bug to the correct address. Alternatively the bug report can beemailed to <R-bugs@R-project.org> or submitted to the Web page at`http://bugs.R-project.org/'.Bug reports on contributed packages should perhaps be sent to thepackage maintainer rather than to R-bugs.10 Acknowledgments******************Of course, many many thanks to Robert and Ross for the R system, and to thepackage writers and porters for adding to it.Special thanks go to Doug Bates, Peter Dalgaard, Paul Gilbert, StefanoIacus, Fritz Leisch, Jim Lindsey, Thomas Lumley, Martin Maechler, Brian D.Ripley, Anthony Rossini, and Andreas Weingessel for their comments whichhelped me improve this FAQ.More to some soon ...