Rev 5046 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
R FAQFrequently Asked Questions on RVersion 0.64-12, 1999/07/02Kurt HornikTable of Contents1 Introduction1.1 Legalese1.2 Obtaining this document1.3 Citing1.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 What mailing lists exist for R?2.9 What is CRAN?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?4 R Web Interfaces5 R Add-On Packages5.1 Which add-on packages exist for R?5.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?7 R Miscellania7.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 Is R Y2K-compliant?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?9 R Bugs9.1 What is a bug?9.2 How to report a bug10 Acknowledgments1 Introduction**************This document contains answers to some of the most frequently askedquestions about R.1.1 Legalese============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.,675 Mass Ave, Cambridge, MA 02139, 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.You can also obtain the R FAQ from the `doc/FAQ' subdirectory of a CRANsite (*Note What is CRAN?::).1.3 Citing==========In publications, please refer to this FAQ as Hornik (1999), "The R FAQ"and give the above, _official_ URL.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 Mac systems.Features specific to the Windows port of R are described in the "FrequentlyAsked Questions for R for Windows"(http://www.stats.ox.ac.uk/pub/R/rw-FAQ.html). If you have information onWindows or Mac systems that you think should be added 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 ofa language 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 a discussion of the differences betweenR and S.R was initially written by Ross Ihaka <ihaka@stat.auckland.ac.nz> andRobert Gentleman <rgentlem@stat.auckland.ac.nz>, who are Senior Lecturersat the Department of Statistics of the University of Auckland in Auckland,New Zealand. In addition, a large group of individuals has contributed toR by sending code and 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, Peter Dalgaard, Robert Gentleman, Kurt Hornik, Ross Ihaka, FriedrichLeisch, Thomas Lumley, Martin Maechler, Guido Masarotto, Paul Murrell,Brian Ripley, Heiner Schwarte, and Luke Tierney.R has a home page at `http://stat.auckland.ac.nz/r/r.html'. It is freesoftware distributed under a GNU-style copyleft, and an official part ofthe GNU project ("GNU S").2.2 What machines does R run on?================================R is being developed for the Unix, Windows and Mac families of operatingsystems.The current version of R will configure and build under a number ofcommon Unix platforms including i386-freebsd, i386-linux, ppc-linux,mips-sgi-irix, alpha-linux, alpha-dec-osf4, sparc-linux, andsparc-sun-solaris, see the file `PLATFORMS' in the R distribution for moreinformation.If you know about other platforms, please drop us a note.2.3 What is the current version of R?=====================================The current stable Unix version is 0.64.2, the unstable one is0.65.0. Typically, new features are introduced in the developmentversions; updates of stable versions are for bug fixes mostly. The Windowsversion tracks the stable Unix version quite closely. The version for theMac is pre-alpha.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?::).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 instructions.Note that as of version 0.62, you need a FORTRAN compiler or `f2c' inaddition to a C compiler to build R. Also (as of 0.60), you need Perlversion 5 to build the documentation. If this is not available on yoursystem, you can obtain precompiled documentation files via CRAN.In the simplest case, untar the R source code, cd to the directory thuscreated, and issue the following commands (at the shell prompt):$ ./configure$ makeIf these commands execute successfully, the R binary and a shell scriptfont-end called `R' are created and copied to the `bin' directory. You cancopy 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 obtain a dvi version of the R manual. This createsthe files `Manual.dvi' (a start of a manual) and `Reference.dvi' (an Robject reference index) in the `doc/manual' subdirectory. These files canbe previewed and printed using standard programs such as `xdvi' and `dvips'.(Note that they have to be built in the source tree.)You can also perform a "system-wide" installation using$ make installThis will install to the following directories:`${prefix}/bin'(some) executables`${prefix}/man/man1'man pages`${prefix}/lib/R'all the rest (libraries, on-line help system, ...)where `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'.)2.5.2 How can R be installed (Windows)--------------------------------------The `bin/ms-windows' directory of a CRAN site currently contains twobinary distributions of R for MS Windows: one by Robert Gentleman in the`windows' subdirectory, and one by Guido Masarotto<guido@sirio.stat.unipd.it> and Brian D. Ripley <ripley@stats.ox.ac.uk> in`windows-9x'. The latter only works on 32 bit versions of Windows (i.e.,95, 98 or NT), the former also on 3.11. See the respective directories formore information. Binary distributions for a large number of add-onpackages (basically all those on CRAN except purely data collections) foruse with the Guido & Brian version are available in the`windows-9x/contrib' subdirectory.Note that when uncompressing the zip files, the pkunzip program needs tobe invoked with the `-D' flag to create subdirectories. Also, be awarethat some decompression programs do not preserve long file names properly.See the R Windows FAQ (http://www.stats.ox.ac.uk/pub/R/rw-FAQ.html) formore details.2.5.3 How can R be installed (Macintosh)----------------------------------------The CRAN `bin/macintosh' directory contains `R.sea.hqx', a binhexedself-extracting archive, and installation instructions in`README.MACINTOSH'. Note that the version in it is nowhere near thequality of the current Unix version.The Power Macintosh port is temporarily on hold.2.6 Are there Unix binaries for R?==================================The `bin/linux' directory contains Debian 2.0 packages for the i386platform (now part of the Debian distribution and maintained by Doug Bates)as well as Red Hat 5.1 packages for the i386, alpha and sparc platforms(maintained by Martyn Plummer, Naoki Takebayashi, and Vin Everett,respectively), S.u.S.E. 5.3 i386 packages by Albrecht Gebhardt, and RPMsfor the ppc platform by Alex Buerkle. (Note that conversion between Debianand Red Hat using Debian's `alien'(1) tool unfortunately only sort ofworks, as the systems use different versions or numbering for libreadlineand libncurses.)There are also `tar' distributions for NEXTSTEP on the i386 and m68kplatforms in `bin/nextstep/i386' and `bin/nextstep/m68k'.No other binary distributions have thus far been made publicallyavailable.2.7 What documentation exists for R?====================================Online documentation for most of the functions and variables in Rexists, and can be printed on-screen by typing `help(NAME)' (or `?NAME') atthe R prompt, where NAME is the name of the topic help is sought for. (Inthe case of unary and binary operators and control-flow special forms, thename may need to be be quoted.)This documentation can also be made available as HTML, and as hardcopyvia LaTeX, see *Note How can R be installed?::. An up-to-date HTML versionis always available for web browsing at `http://stat.ethz.ch/R/manual/'.An R manual ("Notes on R: A Programming Environment for Data Analysisand Graphics") is currently being written, based on the "Notes on S-PLUS"by Bill Venables <venables@stats.adelaide.edu.au> and David Smith<D.M.Smith@lancaster.ac.uk>. The current version can be obtained as`Rnotes.tgz' (LaTeX source) in a CRAN `doc' directory. Note that the"conversion" from S(-PLUS) to R is not complete yet. Further documentationon R and the R API are currently being written.In the absence of an R manual, documentation for S/S-PLUS (see *Note Rand S::) can be used in combination with this FAQ (*note What are thedifferences between R and S?::.). We recommendW. N. Venables and B. D. Ripley (1997), "Modern Applied Statistics withS-PLUS. Second Edition". Springer, ISBN 0-387-98214-0.which has a home page at `http://www.stats.ox.ac.uk/pub/MASS2/' providingadditional material, in particular `R' Complements which describe how touse the book with R. These complements provide both descriptions of someof the differences between R and S, and the modifications needed to run theexamples in the book.More introductory books areP. Spector (1994), "An introduction to S and S-PLUS", Duxbury Press.A. Krause and M. Olsen (1997), "The Basics of S and S-PLUS", Springer.Last, but not least, Ross' and Robert's experience in designing andimplementing R is described in:@article{,author = {Ross Ihaka and Robert Gentleman},title = {R: A Language for Data Analysis and Graphics},journal = {Journal of Computational and Graphical Statistics},year = 1996,volume = 5,number = 3,pages = {299--314}}This is also the reference for R to use in publications.2.8 What mailing lists exist for R?===================================Thanks to Martin Maechler <maechler@stat.math.ethz.ch>, there are threemailing lists devoted to R.`r-announce'This list is for announcements about the development of R and theavailability of new code.`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.`r-help'The `main' R mailing list, for announcements about the development of Rand the availability of new code, questions and answers about problemsand solutions using R, enhancements and patches to the source code anddocumentation of R, comparison and compatibility with S and S-PLUS, andfor the posting of nice examples and benchmarks.Note that the r-announce list is gatewayed into r-help, so you don't needto subscribe to both of them.Send email to <r-help@stat.math.ethz.ch> to reach everyone on the r-helpmailing list. To subscribe (or unsubscribe) to this list send `subscribe'(or `unsubscribe') in the BODY of the message (not in the subject!) to<r-help-request@stat.math.ethz.ch>. Information about the list can beobtained by sending an email with `info' as its contents to<r-help-request@stat.math.ethz.ch>.Subscription and posting to the other lists is done analogously, with`r-help' replaced by `r-announce' and `r-devel', respectively.It is recommended that you send mail to r-help rather than only to the Rdevelopers (who are also subscribed to the list, of course). This may savethem 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/mail/mail.html' file in CRAN. An HTMLarchive of the lists are available via`http://www.ens.gu.edu.au/robertk/R/'.The R Core Team can be reached at <r-core@stat.math.ethz.ch> forcomments and reports.2.9 What is CRAN?=================The "Comprehensive R Archive Network" (CRAN) is a collection of siteswhich carry identical material, consisting of the R distribution(s), thecontributed extensions, documentation for R, and binaries.The CRAN master site can be found at the URL`http://www.ci.tuwien.ac.at/R/' (Austria)and is currently being mirrored daily at`http://SunSITE.auc.dk/R/' (Denmark)`http://www.stat.unipg.it/pub/stat/statlib/R/CRAN/'(Italy)`ftp://ftp.u-aizu.ac.jp/pub/lang/R/CRAN/' (Japan)`ftp://dola.snu.ac.kr/pub/R/CRAN/' (South Korea)`http://stat.ethz.ch/CRAN/' (Switzerland)`http://www.stats.bris.ac.uk/R/' (United Kingdom)`http://lib.stat.cmu.edu/R/CRAN/' (USA/Pennsylvania)`http://cran.stat.wisc.edu/' (USA/Wisconsin)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 for Unix systems (copy of the current CVS tree), as gzippedand bzipped tar files or as two gzipped tar files (ready for 1.4Mfloppies), a wealth of additional contributed code, as well as prebuiltbinaries for various operating systems (Linux, Nextstep, MacOS, MSWin) andpre-formatted help pages. CRAN also provides access to documentation on R,existing mailing lists and the R Bug Tracking system.To "submit" to CRAN, simply upload to`ftp://ftp.ci.tuwien.ac.at/incoming' and send an email to<wwwadmin@ci.tuwien.ac.at>.*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.3 R and S*********3.1 What is S?==============S is a very high level language and an environment for data analysis andgraphics. S was written by Richard A. Becker, John M. Chambers, and AllanR. Wilks of AT&T Bell Laboratories Statistics Research Department.The primary references for S are two books by the creators of S.* Richard A. Becker, John M. Chambers and Allan R. Wilks (1988), "The NewS Language," Chapman & Hall, London.This book is often called the "_Blue Book_".* John M. Chambers and Trevor J. Hastie (1992), "Statistical Models inS," Chapman & Hall, London.This is also called the "_White Book_".There is a huge amount of user-contributed code for S, available at theS Repository (http://lib.stat.cmu.edu) at CMU.See the "Frequently Asked Questions about S"(http://lib.stat.cmu.edu/S/faq) for further information about S.3.2 What is S-PLUS?===================S-PLUS is a value-added version of S sold by Statistical Sciences, Inc.(now a division of Mathsoft, Inc.). S is a subset of S-PLUS, and henceanything which may be done in S may be done in S-PLUS. In addition S-PLUShas extended functionality in a wide variety areas, including robustregression, modern non-parametric regression, time series, survivalanalysis, multivariate analysis, classical statistical tests, qualitycontrol, and graphics drivers. Add-on modules add additional capabilitiesfor wavelet analysis, spatial statistics, and design of experiments.See the MathSoft S-PLUS page (http://www.mathsoft.com/splus.html) forfurther information.3.3 What are the differences between R and S?=============================================3.3.1 Lexical scoping---------------------Whereas the developers of R have tried to stick to the S language asdefined in "The New S Language" (Blue Book, see *Note What is S?::), theyhave adopted the evaluation 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 (and typically, the builtin ones do not).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 provided inthe standard R reference "R: A Language for Data Analysis and Graphics"(*note What documentation exists for R?::.) and a paper on "Lexical Scopeand Statistical Computing" by Robert Gentleman and Ross Ihaka which can beobtained from the `doc/misc' directory of a CRAN site.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 very large piece ofmemory and uses it to store the objects. R performs its own memorymanagement of this piece of memory. Having everything in memory isnecessary because it is not really possible to externally maintain allrelevant "environments" of symbol/value pairs. This difference also seemsto make R _much 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.) R is still in a beta stage, and maycrash from time to time. Hence, for important work you should considersaving often (see *Note How can I save my workspace?::). Otherpossibilities are logging your sessions, or have your R commands stored intext files which can be read 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.* 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 Slanguage definition in the Blue Book as much as possible, and hence reallyis an "implementation" of S. There are some intentional differences wherethe behavior of S is considered "not clean". In general, the rationale isthat R should help you detect programming errors, while at the same timebeing 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 ``$RHOME'/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 `RPROFILE' environment variable. If that variable isunset, the default is ``$RHOME'/etc/Rprofile'. Then, unless`--no-init-file' was given, R searches for a file called `.Rprofile'in the current directory or in the user's home directory (in thatorder) and sources it. It also loads a saved image from `.RData' incase there is one (unless `--no-restore' was specified). If needed,the functions `.First()' and `.Last()' should be defined in theappropriate 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 always use`TRUE' and `FALSE'.* In R, `dyn.load()' can only load _shared libraries_, as created forexample by `R SHLIB'.* Whereas in S, `abs(z)' is the same as `Mod(z)' for complex `z', in Ryou _must_ use `Mod(z)', since `abs()' is a function of real numbersonly.* In R, `attach()' currently only works for lists and data frames (notfor directories). 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 uses only double precision and so can only pass numeric arguments toC/FORTRAN subroutines as double * or DOUBLE PRECISION, respectively.* 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 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 last argument (which corresponds to the right hand side) ofan assignment function must be named `value'. E.g., `fun(a) <- b' isevaluated as `(fun<-)(a, value = b)'.* In S, `substitute' searches for names for substitution in the givenexpression in three places: the actual and the default arguments of thematching call, and the local frame (in that order). R looks in thelocal 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 R, `eval(EXPR, sys.parent())' does not work. Instead, one shoulduse `eval(EXPR, sys.frame(sys.parent())),' which also works in S.* 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.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 couldport to S-PLUS with little effort there will never be much you can do in Rthat you couldn't do in S-PLUS (or vanilla S) if you wanted to. (Note thatusing lexical scoping 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, fixing aspect ratios, and, most importantly, itallows mathematics in plot texts. Unfortunately, this feature still ismostly undocumented, but in a nutshell, "R has TeX inside".4 R Web Interfaces*******************Rcgi* is a CGI WWW interface to R by Mark J Ray <h089@mth.uea.ac.uk>.Recent version have the ability to use "embedded code": you can mix userinput and code, allowing the HTML author to do anything from load in datasets to enter most of the commands for users without writing CGI scripts.Graphical output is possible in PostScript or GIF formats and the executedcode is presented to the user for revision.Demo and download are available from`http://www.mth.uea.ac.uk/~h089/Rcgi/'.*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.A paper on Rweb, providing a detailed explanation of the differentversions of Rweb and an overview of how Rweb works, was published in theJournal of Statistical Software (`http://www.stat.ucla.edu/journals/jss/').5 R Add-On Packages*******************5.1 Which add-on packages exist for R?======================================The R distribution comes with the following extra packages:*eda*Exploratory Data Analysis. Currently only contains functions forrobust line fitting, and median polish and smoothing.*lqs*Resistant regression and covariance estimation.*modreg*MODern REGression: smoothing and local methods.*mva*MultiVariate Analysis. Currently contains code for principalcomponents, canonical correlations, hierarchichal clustering, andmetric multidimensional scaling.*stepfun*Code for dealing with step functions, including empirical cumulativedistribution functions (`ecdf').The following packages are available from the CRAN `src/contrib' area.*KernSmooth*Functions for kernel smoothing (and density estimation) correspondingto the book "Kernel Smoothing" by M. P. Wand and M. C. Jones, 1995.*MASS*Functions and datasets from the main library of Venables and Ripley,"Modern Applied Statistics with S-PLUS" (2nd edition). Contained in`VR'.*NISTnls*A set of test nonlinear least squares examples from NIST, the U.S.National Institute for Standards and Technology.*RmSQL*An interface between R and the mSQL database system.*Rnotes*The data sets for the exercises in Rnotes (*note What documentationexists for R?::.).*acepack*ace (Alternating Conditional Expectations) and avas (Additivity andVAriance Stabilization for regression) for selecting regressiontransformations.*akima*Linear or cubic spline interpolation for irregularly gridded data.*ash*Programs for 1D, 2D and 3D density estimation.*bindata*Generation of correlated artificial binary data.*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.*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.*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.*chron*A package for working with chronological objects (times and dates).*class*Functions for classification (k-nearest neighbor and LVQ). Containedin `VR'.*cluster*Functions for cluster analysis.*coda*Output analysis and diagnostics for Markov Chain Monte Carlo (MCMC)simulations.*ctest*A collection of classical tests, including the Bartlett, Fisher,Kruskal-Wallis, Kolmogorov-Smirnov, and Wilcoxon tests.*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.*e1071*Miscellaneous functions used at the Department of Statistics at TU Wien(E1071).*event*Procedures for event history analysis.*fracdiff*Maximum likelihood estimation of the parameters of a fractionallydifferenced ARIMA(p,d,q) model (Haslett and Raftery, AppliedStatistics, 1989).*funfits*An integrated set of functions for fitting curves and surfacesincluding thin plate splines, kriging and neural networks.*gee*An implementation of the Liang/Zeger generalized estimating equationapproach to GLMs for dependent data.*gnlm*Generalized nonlinear regression models.*growth*Normal theory repeated measurements models.*integrate*Adaptive quadrature in up to 20 dimensions.*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.*lme*Fit and compare Gaussian linear mixed-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).*locfit*Local Regression, likelihood and density estimation.*logspline*Logspline density estimation.*mclust*Model-based cluster analysis.*mlbench*A collection of artificial and real-world machine learning benchmarkproblems, including the Boston housing data.*multiv*Functions for hierarchical clustering, partitioning, bond energyalgorithm, Sammon mapping, PCA and correspondence analysis.*nls*Nonlinear regression routines for R.*nnet*Software for single hidden layer perceptrons ("feed-forward neuralnetworks"), and for multinomial log-linear models. Contained in `VR'.*oz*Functions for plotting Australia's coastline and state boundaries.*pls*Univariate Partial Least Squares Regression.*polymars*Polychotomous regression based on Multivariate Adaptive RegressionSplines.*polynom*A collection of functions to implement a class for univariatepolynomial manipulations.*princurve*Fits a principal curve to a matrix of points in arbitrary dimension.*pspline*Smoothing splines with penalties on order m derivatives.*quadprog*For solving quadratic programming problems.*quantreg*Compute regression quantiles and some related rank statistics.*ratetables*US national and state mortality data (requires *survival4* and*date*), for use with *survival4*.*repeated*Models for non-normal repeated measurements.*rmutil*Tools for repeated measurements.*rpart*Recursive Partitioning.*sgeostat*An object-oriented framework for geostatistical modeling.*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.*spatial*Functions for kriging and point pattern analysis from "Modern AppliedStatistics with S-PLUS" by W. Venables and B. Ripley (1997). Containedin `VR'.*splines*Functions and classes for defining B-spline representations orpolynomial spline representations of regression splines orinterpolation splines.*stable*Density, distribution, quantile and hazard functions of a stablevariate; generalized linear models for the parameters of a stabledistribution.*survival4*Functions for survival analysis, version 4 (requires *splines*).*survival5*Functions for survival analysis, version 5 (requires *splines* andsuggests *date*), the main new feature being penalised (partial)likelihood.*tree*Classification and regression trees.*tripack*A constrained two-dimensional Delaunay triangulation package.*xgobi*Interface to the XGobi program for graphical data analysis.See CRAN `src/contrib/INDEX' 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*bats*Basic time series modelling functions.*dopt*Finding D-optimal experimental designs.*dse*A multivariate time series package (Dynamic Systems Estimation, DSE) byPaul Gilbert <pgilbert@bank-banque-canada.ca> which implements anobject oriented approach to time series models (using classes andmethods in R/S). The package provides state-space models and theKalman filter, VARMA and cointegration models, and numericaldifferentiation. It also contains Troll models as another class (theTroll interface is not yet functional in R). For further informationsee `http://www.bank-banque-canada.ca/pgilbert'.*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.*timeslab*Time series routines.Harald Fekjaer <hfe@math.uio.no> has written *addreg*, a package foradditive hazards regression, which can be obtained from`http://www.med.uio.no/imb/stat/addreg/'.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(which may contain more than one package). First "unpack" the files ofinterest. If you have GNU tar, you can use `tar zxf NAME', otherwise youcan use `gunzip -c NAME | tar xf -'.Let PKGDIR_1, ..., PKGDIR_N be the (relative or absolute) path names ofthe packages to be installed. (In the simplest case, the unpacking createsa single package directory, and its name is used.) To install to thedefault R directory tree (the `library' subdirectory of `RHOME'), type$ R INSTALL PKGDIR_1 ... PKGDIR_Nat the shell prompt. To install to another tree (e.g., your private one),use$ R INSTALL -l LIB PKGDIR_1 ... PKGDIR_Nwhere LIB gives the path to the library tree to install to.You can use several library trees of add-on packages. The easiest wayto tell R to use these is via the environment variable `RLIBS' which shouldbe a colon-separated list of directories at which R library trees arerooted. You do not have to specify the default tree in `RLIBS'. E.g., touse a private tree in `$HOME/lib/R' and a public site-wide tree in`/usr/local/lib/R/site', putRLIBS="$HOME/lib/R:/usr/local/lib/R/site"; export RLIBSinto your (Bourne) shell profile.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 and not documentedPackages in `/usr/local/lib/R/library':MASS Main package of Venables and Ripley's MASSacepack ace() and avas() for selecting regression transformationsbase The R base packageclass Functions for classificationcluster Functions for clusteringctest Classical Testsdate Functions for handling dateseda Exploratory Data Analysisgee Generalized Estimating Equation modelslme Linear mixed effects librarylocfit Local Regression, Likelihood and Density Estimtion.lqs Resistant Regression and Covariance Estimationmodreg Modern regression: smoothing and local methodsmva Classical Multivariate Analysisnnet Software for feed-forward neural networks with a singlehidden layer and for multinomial log-linear models.splines Regression Spline Functions and Classesstepfun Step Functions, including Empirical Distributionssurvival4 Survival analysis (needs `splines')You can "load" the installed package PKG bylibrary(PKG)You can then find out which functions it provides by typing one ofhelp(package = PKG)library(help = PKG)You can unload the loaded package PKG bydetach("package:PKG")5.4 How can add-on packages be removed?=======================================To remove the packages PKG_1, ..., PKG_N from the default library or thelibrary LIB, do$ R REMOVE PKG_1 ... PKG_Nor$ R REMOVE -l LIB PKG_1 ... PKG_Nrespectively.5.5 How can I create an R package?==================================A package consists of a subdirectory containing the files `DESCRIPTION',`INDEX', and `TITLE', and the subdirectories `R', `data', `exec', `man' and`src' (some of which can be missing).The `DESCRIPTION' file contains basic information about the package inthe following format:Package: e1071Version: 0.7-3Author: Compiled by Fritz Leisch <Friedrich.Leisch@ci.tuwien.ac.at>.Description: Miscellaneous functions used at the Department ofStatistics at TU Wien (E1071).Depends:License: GPL version 2 or laterThe license field should contain an explicit statement or a well-knownabbreviation (such as `GPL', `LGPL', `BSD' and `Artistic'), maybe followedby a reference to the actual license file. It is very important that youinclude this information! Otherwise, it may not even be legally correctfor others to distribute copies of the package.The `TITLE' file contains a line giving the name of the package and abrief description. `INDEX' contains a line for each sufficientlyinteresting object in the package, giving its name and a description(functions such as print methods not usually called explicitly might not beincluded). Note that you can automatically create this file usingsomething like `R CMD Rdindex man/*.Rd > INDEX' provided that Perl isavailable on your system.The `R' subdirectory contains code files. The code files to beinstalled must start with a (lower- or uppercase) letter and have one ofthe extensions `.R', `.S', `.q', `.r', or `.s'. We recommend using `.R',as this extension seems to be not used by any other software. It should bepossible to read in the files using `source()', so R objects must becreated by assignments. Note that there has to be no connection betweenthe name of the file and the R objects created by it. If necessary, one ofthese files (historically `zzz.R') should use `library.dynam()' _inside_`.First.lib()' to load compiled code.The `man' subdirectory should contain documentation files for theobjects in the package. The documentation files to be installed must alsostart with a (lower- or uppercase) letter and have the extension `.Rd' (thedefault) or `.rd'.C or FORTRAN source and optionally a `Makefile' for the compiled code isin `src'. A sample `Makefile' can be found in the standard *eda* package.The `data' subdirectory is for additional data files the package makesavailable for loading using `data()'. Currently, data files can have oneof three types as indicated by their extension: plain R code (`.R' or`.r'), tables (`.tab', `.txt', or `.csv'), or `save()' images (`.RData' or`.rda').Finally, `exec' could contain additional executables the package needs,typically Shell or Perl scripts. This mechanism is currently not used byany package, and still experimental.See the documentation for `library()' for more information.The web page `http://www.biostat.washington.edu/~thomas/Rlib.html'maintained by Thomas Lumley provides information on porting S packages to R.*Note What is CRAN?::, for information on uploading a package to CRAN.5.6 How can I contribute to R?==============================R is currently still in alpha (or pre-alpha) state, so simply using itand communicating problems is certainly of great value.One place where functionality is still missing is the modeling softwareas described in "Statistical Models in S" (see *Note What is S?::). `gam'and and the nonlinear modeling code are not there yet.See also the `PROJECTS' file in the top level R source directory.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@ci.tuwien.ac.at>.6 R and Emacs*************6.1 Is there Emacs support for R?=================================There is an Emacs-Lisp interface for interactive statistical programmingand data analysis called ESS ("Emacs Speaks Statistics"). Languagessupported include: S dialects (S 3/4, S-PLUS 3.x, and R), LispStat dialects(XLispStat, ViSta), and SAS. Stata and SPSS dialect (SPSS, PSPP) supportis being examined for possible future implementation (a preliminary Statamode is distributed).ESS grew out of the desire for bug fixes and extensions to S-mode 4.8(which was a GNU Emacs interface to S/S-PLUS version 3 only). Inparticular, XEmacs support as well as extensions to incorporate R weredesired. In addition, with new modes being developed for R, Stata, andSAS, it was felt that providing for a unifying framework would eliminatedifferences in the user interface, as well as to provide for fasterdevelopment of production tools and statistical analysis. Version 5.0 has,for its guts, the basic framework from S-mode. However, it has beencleaned, streamlined, brought closer to conformance as a standard GNU Emacspackage, and redesigned for modularity and reuse.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 (including sending examples to a running R process andpreviewing), interacting with an inferior R process from within Emacs(command-line editing, searchable command history, command-line completionof R object and file names, quick access to object and search lists,transcript recording, and an interface to the help system), and transcriptmanipulation (in particular for re-evaluating commands from transcriptfiles).The latest versions of ESS are available from`http://ess.stat.wisc.edu/pub/ESS/' or `ftp://ess.stat.wisc.edu/pub/ESS/',or via CRAN. The HTML version of the documentation can 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/historymechanism, object name completion, and syntax-based highlighting of theinteraction buffer using Font Lock mode, as well as a very convenientinterface to the R 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. This prompts you for the arguments; in particular,you can increase the memory size this way (*note Why does R run out ofmemory?::.).7 R Miscellania***************7.1 Why does R run out of memory?=================================R (currently) uses a _static_ memory model. This means that when itstarts up, it asks the operating system to reserve a fixed amount of memoryfor it. The size of this chunk cannot be changed subsequently. Hence, itcan happen that not enough memory was allocated, e.g., when trying to readlarge data sets into R.In these cases, you should restart R with more memory available, usingthe command line options `--nsize' and `--vsize'. To understand theseoptions, one needs to know that R maintains separate areas for fixed andvariable sized objects. The first of these is allocated as an array of"cons cells" (Lisp programmers will know what they are, others may think ofthem as the building blocks of the language itself, parse trees, etc.), andthe second are thrown on a "heap". The `--nsize' option can be used tospecify the number of cons cells (each occupying 16 bytes) which R is touse (the default is 200000), and the `--vsize' option to specify the sizeof the vector heap in bytes (the default is 2 MB). Boths options musteither be integers or integers ending with `M', `K', or `k' meaning `Mega'(2^20), (computer) `Kilo' (2^10), or regular `kilo' (1000).E.g., to read in a table of 5000 observations on 40 numeric variables,`R --vsize 6M' should do.Note that the information on where to find vectors and strings on theheap is stored using cons cells. Thus, it may also be necessary toallocate more space for cons cells in order to perform computations withvery "large" variable-size objects.You can find out the current memory consumption (the proportion of heapand cons cells used) by typing `gc()' at the R prompt. This may help youin finding out whether to increase `--vsize' or `--nsize'. Note thatfollowing `gcinfo(TRUE)', automatic garbage collection always prints memoryuse statistics.As of version 0.62.3, R will tell you whether you ran out of cons orheap memory.When using `read.table()', the memory requirements are in fact higherthan anticipated, because the file is first read in as one long stringwhich is then split again. Use `scan()' if possible in case you run out ofmemory when reading in a large table.7.2 Why does sourcing a correct file fail?==========================================R sometimes has problems parsing a file which does not end in a newline.This can happen for example when Emacs is used for editing the file and`next-line-add-newlines' is set to `nil'. To avoid the problem, either set`require-final-newline' to a non-`nil' value in one of your Emacs startupfiles, or make sure R-mode (*note Is there Emacs support for R?::.) is usedfor editing R source files (which locally ensures this setting).Earlier R versions had a similar problem when reading in data files, butthis should have been taken care of now.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())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 pages 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 ofan object and the package containing it, stores some information in thisenvironment. When R tries to evaluate NAME, it loads the correspondingpackage PKG and reevaluates 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 ofglobal "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 escapecharacter, so that for example one can enter a newline as `\n'. When youreally need a `\', you have to escape it with another `\'.Thus, in filenames use something like `"c:\\data\\money.dat"'. You canalso rotate `\' by 90 degrees (`"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.7.12 Is R Y2K-compliant?========================We expect R to be Y2K compliant when compiled and run on a Y2K compliantsystem. In particular R does not internally represent or manipulate datesas two-digit quantities. However, no guarantee of Y2K compliance isprovided for R. R is free software and comes with _no warranty whatsover_.R, like any other programming language, can be used to write programsand manipulate data in ways that are not Y2K compliant.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()' whichnicely prints the summary information and invisibly returns its object.This approach is preferred over having `summary.foo()' print summaryinformation and return something useful, as sometimes you need to grabsomething computed by `summary()' inside a function or similar. In suchcases you don't want anything printed.8.2 How can I debug dynamically loaded code?============================================According to Doug Bates, the secret of symbolic debugging of dynamicallyloaded code is to* Call the debugger on the R executable. In the shell, you can e.g. use`R -d gdb'; see below for debugging from within Emacs.* Start the R program.* At the R prompt, use `dyn.load()' to load your library.* Send an interrupt signal. Inside of GUD mode in Emacs, you send `C-cC-c'. This will put you back to the debugger prompt.* Set the breakpoints in your code.* Continue execution of R by typing `signal 0<RET>'.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 executable (`R.binary'). That way `.gdbinit' can stay in the directorywith the code and be used to set up the environment and the search pathsfor the source, e.g. as follows:set env RHOME /usr/lib/Rset env R_PAPERSIZE letterset env R_PRINTCMD lprdir /usr/lib/R/src/appldir /usr/lib/R/src/maindir /usr/lib/R/src/nmathdir /usr/lib/R/src/unix8.3 How can I inspect R objects when debugging?===============================================In the C implementation underlying R, all objects are so-called SEXPs(from Lisp's "S-expressions" which comes from "symbolic expression"), whichare pointers to data structures called SEXPRECs. (See the file`src/include/Defn.h' in the R sources for the definition of the SEXPRECtype.) For example, letR> DF <- data.frame(a = 1:3, b = 4:6)By setting a breakpoint at `do_get' and typing `get("DF")' at the R prompt,one can find out the address in memory of `DF', e.g.Value returned is $1 = (SEXPREC *) 0x40583e1c(gdb) p *$1$2 = {sxpinfo = {type = 19, obj = 1, named = 1, gp = 0,mark = 0, debug = 0, trace = 0, = 0},attrib = 0x40583e80,u = {vecsxp = {length = 2,type = {c = 0x40634700 "0>X@D>X@0>X@", i = 0x40634700,f = 0x40634700, z = 0x40634700, s = 0x40634700},truelength = 1075851272,},primsxp = {offset = 2},symsxp = {pname = 0x2, value = 0x40634700, internal = 0x40203008},listsxp = {carval = 0x2, cdrval = 0x40634700, tagval = 0x40203008},envsxp = {frame = 0x2, enclos = 0x40634700},closxp = {formals = 0x2, body = 0x40634700, env = 0x40203008},promsxp = {value = 0x2, expr = 0x40634700, env = 0x40203008}}}(Debugger output reformatted for better legibility).Using `PrintValue' one can "inspect" the values of the various elementsof the SEXP, e.g.,(gdb) p PrintValue($1->attrib)$names[1] "a" "b"$row.names[1] "1" "2" "3"$class[1] "data.frame"$3 = void(Make sure, however, to use `PrintValue' on SEXPs with the `obj' bit turnedon only.)To find out where exactly the corresponding information is stored, oneneeds to go "deeper":(gdb) set $a = $1->attrib(gdb) p $a->u.listsxp.tagval->u.symsxp.pname->u.vecsxp.type.c$4 = 0x405d40e8 "names"(gdb) p $a->u.listsxp.carval->u.vecsxp.type.s[1]->u.vecsxp.type.c$5 = 0x40634378 "b"(gdb) p $1->u.vecsxp.type.s[0]->u.vecsxp.type.i[0]$6 = 1(gdb) p $1->u.vecsxp.type.s[1]->u.vecsxp.type.i[1]$7 = 59 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`.Internal()', `.C()' or `.Fortran()' yourself (or in a function youwrote), you can always crash R by using wrong argument types (modes). Thisis 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. Ifa 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; we will have to try to figure out whatthe facts must have been to lead to such speculations. Sometimes this isimpossible. But in any case, it is unnecessary work for us.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 data sets.Perhaps it fails when a variable name is a day of the week. If this is sothen when we got your report we would try out the `data.frame()' command ona large data set, probably with no day of the week variable name, and notsee any problem. There is no way in the world that we could guess that weshould try a day of the week variable name.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 we 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.Invoking R with the `--vanilla' option may help in isolating a bug. Thisensures 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@biostat.ku.dk> or submitted to the Web page at`http://r-bugs.biostat.ku.dk'.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 tothe package writers and porters for adding to it.Special thanks go to Doug Bates, Peter Dalgaard, Paul Gilbert, FritzLeisch, Jim Lindsey, Thomas Lumley, Martin Maechler, Brian D. Ripley,Anthony Rossini, and Andreas Weingessel for their comments which helped meimprove this FAQ.More to some soon ...