<html lang="en"> <head> <title>R Language Definition</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="R Language Definition"> <meta name="generator" content="makeinfo 4.13"> <link title="Top" rel="top" href="#Top"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- This manual is for R, version 3.0.2 (2013-09-25). Copyright (C) 2000-2013 R Core Team Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the R Core Team. --> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } body {margin-left: 5%; margin-right: 5%;} H1 { background: white; color: rgb(25%, 25%, 25%); font-family: monospace; font-size: xx-large; text-align: center } H2 { background: white; color: rgb(40%, 40%, 40%); font-family: monospace; font-size: x-large; text-align: center } H3 { background: white; color: rgb(40%, 40%, 40%); font-family: monospace; font-size: large } H4 { background: white; color: rgb(40%, 40%, 40%); font-family: monospace } span.samp{font-family: monospace} span.command{font-family: monospace} span.option{font-family: monospace} span.file{font-family: monospace} span.env{font-family: monospace} ul { margin-top: 0.25ex; margin-bottom: 0.25ex; } li { margin-top: 0.25ex; margin-bottom: 0.25ex; } p { margin-top: 0.6ex; margin-bottom: 1.2ex; } --></style> </head> <body> <h1 class="settitle">R Language Definition</h1> <div class="contents"> <h2>Table of Contents</h2> <ul> <li><a name="toc_Top" href="#Top">R Language Definition</a> <li><a name="toc_Introduction" href="#Introduction">1 Introduction</a> <li><a name="toc_Objects" href="#Objects">2 Objects</a> <ul> <li><a href="#Basic-types">2.1 Basic types</a> <ul> <li><a href="#Vector-objects">2.1.1 Vectors</a> <li><a href="#List-objects">2.1.2 Lists</a> <li><a href="#Language-objects">2.1.3 Language objects</a> <ul> <li><a href="#Symbol-objects">2.1.3.1 Symbol objects</a> </li></ul> <li><a href="#Expression-objects">2.1.4 Expression objects</a> <li><a href="#Function-objects">2.1.5 Function objects</a> <li><a href="#NULL-object">2.1.6 NULL</a> <li><a href="#Builtin-objects-and-special-forms">2.1.7 Builtin objects and special forms</a> <li><a href="#Promise-objects">2.1.8 Promise objects</a> <li><a href="#Dot_002ddot_002ddot">2.1.9 Dot-dot-dot</a> <li><a href="#Environment-objects">2.1.10 Environments</a> <li><a href="#Pairlist-objects">2.1.11 Pairlist objects</a> <li><a href="#Any_002dtype">2.1.12 The “Any” type</a> </li></ul> <li><a href="#Attributes">2.2 Attributes</a> <ul> <li><a href="#Names">2.2.1 Names</a> <li><a href="#Dimensions">2.2.2 Dimensions</a> <li><a href="#Dimnames">2.2.3 Dimnames</a> <li><a href="#Classes">2.2.4 Classes</a> <li><a href="#Time-series-attributes">2.2.5 Time series attributes</a> <li><a href="#Copying-of-attributes">2.2.6 Copying of attributes</a> </li></ul> <li><a href="#Special-compound-objects">2.3 Special compound objects</a> <ul> <li><a href="#Factors">2.3.1 Factors</a> <li><a href="#Data-frame-objects">2.3.2 Data frame objects</a> </li></ul> </li></ul> <li><a name="toc_Evaluation-of-expressions" href="#Evaluation-of-expressions">3 Evaluation of expressions</a> <ul> <li><a href="#Simple-evaluation">3.1 Simple evaluation</a> <ul> <li><a href="#Constants">3.1.1 Constants</a> <li><a href="#Symbol-lookup">3.1.2 Symbol lookup</a> <li><a href="#Function-calls">3.1.3 Function calls</a> <li><a href="#Operators">3.1.4 Operators</a> </li></ul> <li><a href="#Control-structures">3.2 Control structures</a> <ul> <li><a href="#if">3.2.1 if</a> <li><a href="#Looping">3.2.2 Looping</a> <li><a href="#repeat">3.2.3 repeat</a> <li><a href="#while">3.2.4 while</a> <li><a href="#for">3.2.5 for</a> <li><a href="#switch">3.2.6 switch</a> </li></ul> <li><a href="#Elementary-arithmetic-operations">3.3 Elementary arithmetic operations</a> <ul> <li><a href="#Recycling-rules">3.3.1 Recycling rules</a> <li><a href="#Propagation-of-names">3.3.2 Propagation of names</a> <li><a href="#Dimensional-attributes">3.3.3 Dimensional attributes</a> <li><a href="#NA-handling">3.3.4 NA handling</a> </li></ul> <li><a href="#Indexing">3.4 Indexing</a> <ul> <li><a href="#Indexing-by-vectors">3.4.1 Indexing by vectors</a> <li><a href="#Indexing-matrices-and-arrays">3.4.2 Indexing matrices and arrays</a> <li><a href="#Indexing-other-structures">3.4.3 Indexing other structures</a> <li><a href="#Subset-assignment">3.4.4 Subset assignment</a> </li></ul> <li><a href="#Scope-of-variables">3.5 Scope of variables</a> <ul> <li><a href="#Global-environment">3.5.1 Global environment</a> <li><a href="#Lexical-environment">3.5.2 Lexical environment</a> <li><a href="#Stacks">3.5.3 The call stack</a> <li><a href="#Search-path">3.5.4 Search path</a> </li></ul> </li></ul> <li><a name="toc_Functions" href="#Functions">4 Functions</a> <ul> <li><a href="#Writing-functions">4.1 Writing functions</a> <ul> <li><a href="#Syntax-and-examples">4.1.1 Syntax and examples</a> <li><a href="#Arguments">4.1.2 Arguments</a> </li></ul> <li><a href="#Functions-as-objects">4.2 Functions as objects</a> <li><a href="#Evaluation">4.3 Evaluation</a> <ul> <li><a href="#Evaluation-environment">4.3.1 Evaluation environment</a> <li><a href="#Argument-matching">4.3.2 Argument matching</a> <li><a href="#Argument-evaluation">4.3.3 Argument evaluation</a> <li><a href="#Scope">4.3.4 Scope</a> </li></ul> </li></ul> <li><a name="toc_Object_002doriented-programming" href="#Object_002doriented-programming">5 Object-oriented programming</a> <ul> <li><a href="#Definition">5.1 Definition</a> <li><a href="#Inheritance">5.2 Inheritance</a> <li><a href="#Method-dispatching">5.3 Method dispatching</a> <li><a href="#UseMethod">5.4 UseMethod</a> <li><a href="#NextMethod">5.5 NextMethod</a> <li><a href="#Group-methods">5.6 Group methods</a> <li><a href="#Writing-methods">5.7 Writing methods</a> </li></ul> <li><a name="toc_Computing-on-the-language" href="#Computing-on-the-language">6 Computing on the language</a> <ul> <li><a href="#Direct-manipulation-of-language-objects">6.1 Direct manipulation of language objects</a> <li><a href="#Substitutions">6.2 Substitutions</a> <li><a href="#More-on-evaluation">6.3 More on evaluation</a> <li><a href="#Evaluation-of-expression-objects">6.4 Evaluation of expression objects</a> <li><a href="#Manipulation-of-function-calls">6.5 Manipulation of function calls</a> <li><a href="#Manipulation-of-functions">6.6 Manipulation of functions</a> </li></ul> <li><a name="toc_System-and-foreign-language-interfaces" href="#System-and-foreign-language-interfaces">7 System and foreign language interfaces</a> <ul> <li><a href="#Operating-system-access">7.1 Operating system access</a> <li><a href="#Foreign-language-interfaces">7.2 Foreign language interfaces</a> <li><a href="#_002eInternal-and-_002ePrimitive">7.3 .Internal and .Primitive</a> </li></ul> <li><a name="toc_Exception-handling" href="#Exception-handling">8 Exception handling</a> <ul> <li><a href="#stop">8.1 stop</a> <li><a href="#warning">8.2 warning</a> <li><a href="#on_002eexit">8.3 on.exit</a> <li><a href="#Error-options">8.4 Error options</a> </li></ul> <li><a name="toc_Debugging" href="#Debugging">9 Debugging</a> <ul> <li><a href="#browser">9.1 browser</a> <li><a href="#debug_002fundebug">9.2 debug/undebug</a> <li><a href="#trace_002funtrace">9.3 trace/untrace</a> <li><a href="#traceback">9.4 traceback</a> </li></ul> <li><a name="toc_Parser" href="#Parser">10 Parser</a> <ul> <li><a href="#The-parsing-process">10.1 The parsing process</a> <ul> <li><a href="#Modes-of-parsing">10.1.1 Modes of parsing</a> <li><a href="#Internal-representation">10.1.2 Internal representation</a> <li><a href="#Deparsing">10.1.3 Deparsing</a> </li></ul> <li><a href="#Comments">10.2 Comments</a> <li><a href="#Tokens">10.3 Tokens</a> <ul> <li><a href="#Literal-constants">10.3.1 Constants</a> <li><a href="#Identifiers">10.3.2 Identifiers</a> <li><a href="#Reserved-words">10.3.3 Reserved words</a> <li><a href="#Special-operators">10.3.4 Special operators</a> <li><a href="#Separators">10.3.5 Separators</a> <li><a href="#Operator-tokens">10.3.6 Operator tokens</a> <li><a href="#Grouping">10.3.7 Grouping</a> <li><a href="#Indexing-tokens">10.3.8 Indexing tokens</a> </li></ul> <li><a href="#Expressions">10.4 Expressions</a> <ul> <li><a href="#Function-calls-_0028expressions_0029">10.4.1 Function calls</a> <li><a href="#Infix-and-prefix-operators">10.4.2 Infix and prefix operators</a> <li><a href="#Index-constructions">10.4.3 Index constructions</a> <li><a href="#Compound-expressions">10.4.4 Compound expressions</a> <li><a href="#Flow-control-elements">10.4.5 Flow control elements</a> <li><a href="#Function-definitions">10.4.6 Function definitions</a> </li></ul> <li><a href="#Directives">10.5 Directives</a> </li></ul> <li><a name="toc_Function-and-Variable-Index" href="#Function-and-Variable-Index">Function and Variable Index</a> <li><a name="toc_Concept-Index" href="#Concept-Index">Concept Index</a> <li><a name="toc_References" href="#References">Appendix A References</a> </li></ul> </div> <!-- @end ifnothtml --> <div class="node"> <a name="Top"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Introduction">Introduction</a>, Previous: <a rel="previous" accesskey="p" href="#dir">(dir)</a>, Up: <a rel="up" accesskey="u" href="#dir">(dir)</a> </div> <h2 class="unnumbered">R Language Definition</h2> <p>This is an introduction to the R language, explaining evaluation, parsing, object oriented programming, computing on the language, and so forth. <p>This manual is for R, version 3.0.2 (2013-09-25). <p>Copyright © 2000–2013 R Core Team <blockquote> Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. <p>Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. <p>Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the R Core Team. </blockquote> <ul class="menu"> <li><a accesskey="1" href="#Introduction">Introduction</a> <li><a accesskey="2" href="#Objects">Objects</a> <li><a accesskey="3" href="#Evaluation-of-expressions">Evaluation of expressions</a> <li><a accesskey="4" href="#Functions">Functions</a> <li><a accesskey="5" href="#Object_002doriented-programming">Object-oriented programming</a> <li><a accesskey="6" href="#Computing-on-the-language">Computing on the language</a> <li><a accesskey="7" href="#System-and-foreign-language-interfaces">System and foreign language interfaces</a> <li><a accesskey="8" href="#Exception-handling">Exception handling</a> <li><a accesskey="9" href="#Debugging">Debugging</a> <li><a href="#Parser">Parser</a> <li><a href="#Function-and-Variable-Index">Function and Variable Index</a> <li><a href="#Concept-Index">Concept Index</a> <li><a href="#References">References</a> </ul> <div class="node"> <a name="Introduction"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Objects">Objects</a>, Previous: <a rel="previous" accesskey="p" href="#Top">Top</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <!-- node-name, next, previous, up --> <h2 class="chapter">1 Introduction</h2> <p>R is a system for statistical computation and graphics. It provides, among other things, a programming language, high level graphics, interfaces to other languages and debugging facilities. This manual details and defines the R language. <p>The R language is a dialect of S which was designed in the 1980s and has been in widespread use in the statistical community since. Its principal designer, John M. Chambers, was awarded the 1998 ACM Software Systems Award for S. <p>The language syntax has a superficial similarity with C, but the semantics are of the FPL (functional programming language) variety with stronger affinities with Lisp and <acronym>APL</acronym>. In particular, it allows “computing on the language”, which in turn makes it possible to write functions that take expressions as input, something that is often useful for statistical modeling and graphics. <p>It is possible to get quite far using R interactively, executing <a name="index-expression-1"></a>simple expressions from the command line. Some users may never need to go beyond that level, others will want to write their own functions either in an ad hoc fashion to systematize repetitive work or with the perspective of writing add-on packages for new functionality. <p>The purpose of this manual is to document the language <em>per se</em>. That is, the objects that it works on, and the details of the expression evaluation process, which are useful to know when programming R functions. Major subsystems for specific tasks, such as graphics, are only briefly described in this manual and will be documented separately. <p>Although much of the text will equally apply to S, there are also some substantial differences, and in order not to confuse the issue we shall concentrate on describing R. <p>The design of the language contains a number of fine points and common pitfalls which may surprise the user. Most of these are due to consistency considerations at a deeper level, as we shall explain. There are also a number of useful shortcuts and idioms, which allow the user to express quite complicated operations succinctly. Many of these become natural once one is familiar with the underlying concepts. In some cases, there are multiple ways of performing a task, but some of the techniques will rely on the language implementation, and others work at a higher level of abstraction. In such cases we shall indicate the preferred usage. <p>Some familiarity with R is assumed. This is not an introduction to R but rather a programmers' reference manual. Other manuals provide complementary information: in particular <a href="R-intro.html#Preface">Preface</a> provides an introduction to R and <a href="R-exts.html#System-and-foreign-language-interfaces">System and foreign language interfaces</a> details how to extend R using compiled code. <div class="node"> <a name="Objects"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Evaluation-of-expressions">Evaluation of expressions</a>, Previous: <a rel="previous" accesskey="p" href="#Introduction">Introduction</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">2 Objects</h2> <!-- needs to be clarified. What is a pointer, what is the pointed object, --> <!-- what is the context of the pointed object? --> <p>In every computer language <a name="index-variable-2"></a>variables provide a means of accessing the data stored in memory. R does not provide direct access to the computer's memory but rather provides a number of specialized data structures we will refer to as <a name="index-object-3"></a>objects. These objects are referred to through symbols or variables. In R, however, the symbols are themselves objects and can be manipulated in the same way as any other object. This is different from many other languages and has wide ranging effects. <p>In this chapter we provide preliminary descriptions of the various data structures provided in R. More detailed discussions of many of them will be found in the subsequent chapters. The R specific function <code>typeof</code> <a name="index-typeof-4"></a><a name="index-type-5"></a>returns the <dfn>type</dfn> of an R object. Note that in the C code underlying R, all objects are pointers to a structure with typedef <code>SEXPREC</code>; the different R data types are represented in C by <code>SEXPTYPE</code>, which determines how the information in the various parts of the structure is used. <p>The following table describes the possible values returned by <code>typeof</code> and what they are. <blockquote> <p><table summary=""><tr align="left"><td valign="top" width="20%"><code>"NULL"</code> </td><td valign="top" width="70%">NULL <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"symbol"</code> </td><td valign="top" width="70%">a variable name <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"pairlist"</code></td><td valign="top" width="70%">a pairlist object (mainly internal) <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"closure"</code> </td><td valign="top" width="70%">a function <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"environment"</code> </td><td valign="top" width="70%">an environment <a name="index-evaluation_002c-lazy-6"></a><br></td></tr><tr align="left"><td valign="top" width="20%"><code>"promise"</code> </td><td valign="top" width="70%">an object used to implement lazy evaluation <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"language"</code> </td><td valign="top" width="70%">an R language construct <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"special"</code> </td><td valign="top" width="70%">an internal function that does not evaluate its arguments <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"builtin"</code> </td><td valign="top" width="70%">an internal function that evaluates its arguments <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"char"</code> </td><td valign="top" width="70%">a ‘scalar’ string object (internal only) *** <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"logical"</code> </td><td valign="top" width="70%">a vector containing logical values <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"integer"</code> </td><td valign="top" width="70%">a vector containing integer values <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"double"</code> </td><td valign="top" width="70%">a vector containing real values <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"complex"</code> </td><td valign="top" width="70%">a vector containing complex values <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"character"</code> </td><td valign="top" width="70%">a vector containing character values <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"..."</code> </td><td valign="top" width="70%">the special variable length argument *** <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"any"</code> </td><td valign="top" width="70%">a special type that matches all types: there are no objects of this type <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"expression"</code> </td><td valign="top" width="70%">an expression object <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"list"</code> </td><td valign="top" width="70%">a list <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"bytecode"</code> </td><td valign="top" width="70%">byte code (internal only) *** <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"externalptr"</code> </td><td valign="top" width="70%">an external pointer object <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"weakref"</code> </td><td valign="top" width="70%">a weak reference object <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"raw"</code> </td><td valign="top" width="70%">a vector containing bytes <br></td></tr><tr align="left"><td valign="top" width="20%"><code>"S4"</code> </td><td valign="top" width="70%">an S4 object which is not a simple object <br></td></tr></table> </blockquote> <p class="noindent">Users cannot easily get hold of objects of types marked with a ‘***’. <p><a name="index-mode-7"></a><a name="index-mode-8"></a>Function <code>mode</code> gives information about the <dfn>mode</dfn> of an object in the sense of Becker, Chambers & Wilks (1988), and is more compatible with other implementations of the S language. <!-- FIXME: --> <!-- Should say that many R functions, such as vector(), actually have an --> <!-- argument ‘mode’ rather than ‘type’. E.g., vector(mode = "double") --> <!-- actually creates an object of *type* "double" but *mode* "numeric". --> <!-- </FIXME> --> <a name="index-storage_002emode-9"></a>Finally, the function <code>storage.mode</code> returns the <dfn>storage mode</dfn> of its argument in the sense of Becker et al. (1988). It is generally used when calling functions written in another language, such as C or FORTRAN, to ensure that R objects have the data type expected by the routine being called. (In the S language, vectors with integer or real values are both of mode <code>"numeric"</code>, so their storage modes need to be distinguished.) <pre class="example"> > x <- 1:3 > typeof(x) [1] "integer" > mode(x) [1] "numeric" > storage.mode(x) [1] "integer" </pre> <p>R <a name="index-object-10"></a>objects are often coerced to different <a name="index-type-11"></a>types during computations. There are also many functions available to perform explicit <a name="index-coercion-12"></a>coercion. When programming in the R language the type of an object generally doesn't affect the computations, however, when dealing with foreign languages or the operating system it is often necessary to ensure that an object is of the correct type. <ul class="menu"> <li><a accesskey="1" href="#Basic-types">Basic types</a> <li><a accesskey="2" href="#Attributes">Attributes</a> <li><a accesskey="3" href="#Special-compound-objects">Special compound objects</a> </ul> <div class="node"> <a name="Basic-types"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Attributes">Attributes</a>, Previous: <a rel="previous" accesskey="p" href="#Objects">Objects</a>, Up: <a rel="up" accesskey="u" href="#Objects">Objects</a> </div> <p><a name="index-type-13"></a> <h3 class="section">2.1 Basic types</h3> <ul class="menu"> <li><a accesskey="1" href="#Vector-objects">Vector objects</a> <li><a accesskey="2" href="#List-objects">List objects</a> <li><a accesskey="3" href="#Language-objects">Language objects</a> <li><a accesskey="4" href="#Expression-objects">Expression objects</a> <li><a accesskey="5" href="#Function-objects">Function objects</a> <li><a accesskey="6" href="#NULL-object">NULL object</a> <li><a accesskey="7" href="#Builtin-objects-and-special-forms">Builtin objects and special forms</a> <li><a accesskey="8" href="#Promise-objects">Promise objects</a> <li><a accesskey="9" href="#Dot_002ddot_002ddot">Dot-dot-dot</a> <li><a href="#Environment-objects">Environment objects</a> <li><a href="#Pairlist-objects">Pairlist objects</a> <li><a href="#Any_002dtype">Any-type</a> </ul> <div class="node"> <a name="Vector-objects"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#List-objects">List objects</a>, Previous: <a rel="previous" accesskey="p" href="#Basic-types">Basic types</a>, Up: <a rel="up" accesskey="u" href="#Basic-types">Basic types</a> </div> <h4 class="subsection">2.1.1 Vectors</h4> <p><a name="index-vector-14"></a>Vectors can be thought of as contiguous cells containing data. Cells are accessed through <a name="index-index-15"></a>indexing operations such as <code>x[5]</code>. More details are given in <a href="#Indexing">Indexing</a>. <!-- @ref{Data structures} --> <p><a name="index-type-16"></a><a name="index-mode-17"></a><a name="index-atomic-18"></a>R has six basic (‘atomic’) vector types: logical, integer, real, complex, string (or character) and raw. The modes and storage modes for the different vector types are listed in the following table. <blockquote> <p><table summary=""><tr align="left"><th valign="top">typeof </th><th valign="top">mode </th><th valign="top">storage.mode <br></th></tr><tr align="left"><td valign="top"><code>logical</code> </td><td valign="top"><code>logical</code> </td><td valign="top"><code>logical</code> <br></td></tr><tr align="left"><td valign="top"><code>integer</code> </td><td valign="top"><code>numeric</code> </td><td valign="top"><code>integer</code> <br></td></tr><tr align="left"><td valign="top"><code>double</code> </td><td valign="top"><code>numeric</code> </td><td valign="top"><code>double</code> <br></td></tr><tr align="left"><td valign="top"><code>complex</code> </td><td valign="top"><code>complex</code> </td><td valign="top"><code>complex</code> <br></td></tr><tr align="left"><td valign="top"><code>character</code> </td><td valign="top"><code>character</code> </td><td valign="top"><code>character</code> <br></td></tr><tr align="left"><td valign="top"><code>raw</code> </td><td valign="top"><code>raw</code> </td><td valign="top"><code>raw</code> <br></td></tr></table> </blockquote> <p>Single numbers, such as <code>4.2</code>, and strings, such as <code>"four point two"</code> are still vectors, of length 1; there are no more basic types. Vectors with length zero are possible (and useful). <p>String vectors have mode and storage mode <code>"character"</code>. A single element of a character vector is often referred to as a <em>character string</em>. <div class="node"> <a name="List-objects"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Language-objects">Language objects</a>, Previous: <a rel="previous" accesskey="p" href="#Vector-objects">Vector objects</a>, Up: <a rel="up" accesskey="u" href="#Basic-types">Basic types</a> </div> <h4 class="subsection">2.1.2 Lists</h4> <p>Lists (“generic vectors”) are another kind of data storage. Lists have elements, each of which can contain any type of R object, i.e. the elements of a list do not have to be of the same type. List elements are accessed through three different <a name="index-index-19"></a>indexing operations. These are explained in detail in <a href="#Indexing">Indexing</a>. <!-- @ref{Data structures}. --> <p>Lists are vectors, and the basic vector types are referred to as <em>atomic vectors</em> where it is necessary to exclude lists. <div class="node"> <a name="Language-objects"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Expression-objects">Expression objects</a>, Previous: <a rel="previous" accesskey="p" href="#List-objects">List objects</a>, Up: <a rel="up" accesskey="u" href="#Basic-types">Basic types</a> </div> <h4 class="subsection">2.1.3 Language objects</h4> <p>There are three types of objects that constitute the R language. They are <em>calls</em>, <em>expressions</em>, and <em>names</em>. <a name="index-call-20"></a><a name="index-expression-21"></a><a name="index-name-22"></a><!-- FIXME: --> <!-- Better consistently refer to objects of type "expression" as --> <!-- `‘expression objects’' ... --> Since R has objects of type <code>"expression"</code> we will try to avoid the use of the word expression in other contexts. In particular syntactically correct expressions will be referred to as <em>statements</em>. <!-- </FIXME> --> <a name="index-statement-23"></a> These objects have modes <code>"call"</code>, <code>"expression"</code>, and <code>"name"</code>, respectively. <!-- FIXME: Shouldn't we explain their types? --> <p>They can be created directly from expressions using the <code>quote</code> mechanism and converted to and from lists by the <code>as.list</code> and <code>as.call</code> functions. <a name="index-quote-24"></a><a name="index-as_002elist-25"></a><a name="index-as_002ecall-26"></a>Components of the <a name="index-parsing-27"></a>parse tree can be extracted using the standard indexing operations. <ul class="menu"> <li><a accesskey="1" href="#Symbol-objects">Symbol objects</a> </ul> <div class="node"> <a name="Symbol-objects"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Language-objects">Language objects</a>, Up: <a rel="up" accesskey="u" href="#Language-objects">Language objects</a> </div> <h5 class="subsubsection">2.1.3.1 Symbol objects</h5> <p><a name="index-symbol-28"></a>Symbols refer to R <a name="index-object-29"></a>objects. The <a name="index-name-30"></a>name of any R object is usually a symbol. Symbols can be created through the functions <code>as.name</code> and <code>quote</code>. <p><a name="index-symbol-31"></a><a name="index-mode-32"></a>Symbols have mode <code>"name"</code>, storage mode <code>"symbol"</code>, and type <code>"symbol"</code>. They can be <a name="index-coercion-33"></a>coerced to and from character strings using <code>as.character</code> and <code>as.name</code>. <a name="index-as_002echaracter-34"></a><a name="index-as_002ename-35"></a><a name="index-parsing-36"></a>They naturally appear as atoms of parsed expressions, try e.g. <code>as.list(quote(x + y))</code>. <div class="node"> <a name="Expression-objects"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Function-objects">Function objects</a>, Previous: <a rel="previous" accesskey="p" href="#Language-objects">Language objects</a>, Up: <a rel="up" accesskey="u" href="#Basic-types">Basic types</a> </div> <h4 class="subsection">2.1.4 Expression objects</h4> <p>In R one can have objects of type <code>"expression"</code>. An <em>expression</em> contains one or more statements. A statement is a syntactically correct collection of <a name="index-token-37"></a>tokens. <a name="index-expression-object-38"></a>Expression objects are special language objects which contain parsed but unevaluated R statements. The main difference is that an expression object can contain several such expressions. Another more subtle difference is that objects of type <code>"expression"</code> are only <a name="index-evaluation_002c-expression-39"></a>evaluated when explicitly passed to <code>eval</code>, whereas other language objects may get evaluated in some unexpected cases. <p>An <a name="index-expression-object-40"></a>expression object behaves much like a list and its components should be accessed in the same way as the components of a list. <div class="node"> <a name="Function-objects"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#NULL-object">NULL object</a>, Previous: <a rel="previous" accesskey="p" href="#Expression-objects">Expression objects</a>, Up: <a rel="up" accesskey="u" href="#Basic-types">Basic types</a> </div> <h4 class="subsection">2.1.5 Function objects</h4> <p><a name="index-function-41"></a>In R functions are objects and can be manipulated in much the same way as any other object. Functions (or more precisely, function closures) have three basic components: a formal argument list, a body and an <a name="index-environment-42"></a>environment. The argument list is a comma-separated list of arguments. An <a name="index-argument-43"></a>argument can be a symbol, or a ‘<samp><var>symbol</var><span class="samp"> = </span><var>default</var></samp>’ construct, or the special argument ‘<samp><span class="samp">...</span></samp>’. The second form of argument is used to specify a default value for an argument. This value will be used if the function is called without any value specified for that argument. The ‘<samp><span class="samp">...</span></samp>’ argument is special and can contain any number of arguments. It is generally used if the number of arguments is unknown or in cases where the arguments will be passed on to another function. <p>The body is a parsed R statement. It is usually a collection of statements in braces but it can be a single statement, a symbol or even a constant. <p>A function's <a name="index-function-44"></a><a name="index-environment-45"></a>environment is the environment that was active at the time that the function was created. Any symbols bound in that environment are <em>captured</em> and available to the function. This combination of the code of the function and the bindings in its environment is called a ‘function closure’, a term from functional programming theory. In this document we generally use the term ‘function’, but use ‘closure’ to emphasize the importance of the attached environment. <p>It is possible to extract and manipulate the three parts of a closure object using <code>formals</code>, <code>body</code>, and <code>environment</code> constructs (all three can also be used on the left hand side of <a name="index-assignment-46"></a>assignments). <a name="index-formals-47"></a><a name="index-body-48"></a><a name="index-environment-49"></a>The last of these can be used to remove unwanted environment capture. <p>When a function is called, a new environment (called the <em>evaluation environment</em>) is created, whose enclosure (see <a href="#Environment-objects">Environment objects</a>) is the environment from the function closure. This new environment is initially populated with the unevaluated arguments to the function; as evaluation proceeds, local variables are created within it. <p><a name="index-function-50"></a>There is also a facility for converting functions to and from list structures using <code>as.list</code> and <code>as.function</code>. <a name="index-as_002efunction-51"></a>These have been included to provide compatibility with S and their use is discouraged. <div class="node"> <a name="NULL-object"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Builtin-objects-and-special-forms">Builtin objects and special forms</a>, Previous: <a rel="previous" accesskey="p" href="#Function-objects">Function objects</a>, Up: <a rel="up" accesskey="u" href="#Basic-types">Basic types</a> </div> <h4 class="subsection">2.1.6 NULL</h4> <p>There is a special object called <code>NULL</code>. It is used whenever there is a need to indicate or specify that an object is absent. It should not be confused with a vector or list of zero length. <a name="index-NULL-52"></a> The <code>NULL</code> object has no type and no modifiable properties. There is only one <code>NULL</code> object in R, to which all instances refer. To test for <code>NULL</code> use <code>is.null</code>. You cannot set attributes on <code>NULL</code>. <div class="node"> <a name="Builtin-objects-and-special-forms"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Promise-objects">Promise objects</a>, Previous: <a rel="previous" accesskey="p" href="#NULL-object">NULL object</a>, Up: <a rel="up" accesskey="u" href="#Basic-types">Basic types</a> </div> <h4 class="subsection">2.1.7 Builtin objects and special forms</h4> <p>These two kinds of object contain the builtin <a name="index-function-53"></a><a name="index-g_t_002ePrimitive-54"></a><a name="index-g_t_002eInternal-55"></a>functions of R, i.e., those that are displayed as <code>.Primitive</code> in code listings (as well as those accessed via the <code>.Internal</code> function and hence not user-visible as objects). The difference between the two lies in the argument handling. Builtin functions have all their arguments evaluated and passed to the internal function, in accordance with <em>call-by-value</em>, whereas special functions pass the unevaluated arguments to the internal function. <p>From the R language, these objects are just another kind of function. The <code>is.primitive</code> function can distinguish them from interpreted <a name="index-function-56"></a>functions. <div class="node"> <a name="Promise-objects"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Dot_002ddot_002ddot">Dot-dot-dot</a>, Previous: <a rel="previous" accesskey="p" href="#Builtin-objects-and-special-forms">Builtin objects and special forms</a>, Up: <a rel="up" accesskey="u" href="#Basic-types">Basic types</a> </div> <h4 class="subsection">2.1.8 Promise objects</h4> <p><a name="index-promise-57"></a>Promise objects are part of R's lazy evaluation mechanism. They contain three slots: a value, an expression, and an <a name="index-environment-58"></a>environment. When a <a name="index-function-59"></a><a name="index-function-argument-60"></a>function is called the arguments are matched and then each of the formal arguments is bound to a promise. The expression that was given for that formal argument and a pointer to the environment the function was called from are stored in the promise. <p>Until that argument is accessed there is no <em>value</em> associated with the promise. When the argument is accessed, the stored expression is <a name="index-evaluation_002c-expression-61"></a>evaluated in the stored environment, and the result is returned. The result is also saved by the promise. The <code>substitute</code> function will extract the content of the expression slot. This allows the programmer to access either the value or the expression associated with the promise. <p>Within the R language, promise objects are almost only seen implicitly: actual function arguments are of this type. There is also a <code>delayedAssign</code> function that will make a promise out of an expression. There is generally no way in R code to check whether an object is a promise or not, nor is there a way to use R code to determine the environment of a promise. <div class="node"> <a name="Dot-dot-dot"></a> <a name="Dot_002ddot_002ddot"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Environment-objects">Environment objects</a>, Previous: <a rel="previous" accesskey="p" href="#Promise-objects">Promise objects</a>, Up: <a rel="up" accesskey="u" href="#Basic-types">Basic types</a> </div> <h4 class="subsection">2.1.9 Dot-dot-dot</h4> <p>The ‘<samp><span class="samp">...</span></samp>’ object type is stored as a type of pairlist. The components of ‘<samp><span class="samp">...</span></samp>’ can be accessed in the usual pairlist manner from C code, but is not easily accessed as an object in interpreted code. The object can be captured as a list, so for example in <code>table</code> one sees <pre class="example"> args <- list(...) ## .... for (a in args) { ## .... </pre> <p><a name="index-function-62"></a><a name="index-function-argument-63"></a>If a function has ‘<samp><span class="samp">...</span></samp>’ as a formal argument then any actual arguments that do not match a formal argument are matched with ‘<samp><span class="samp">...</span></samp>’. <div class="node"> <a name="Environment-objects"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Pairlist-objects">Pairlist objects</a>, Previous: <a rel="previous" accesskey="p" href="#Dot_002ddot_002ddot">Dot-dot-dot</a>, Up: <a rel="up" accesskey="u" href="#Basic-types">Basic types</a> </div> <h4 class="subsection">2.1.10 Environments</h4> <p><a name="index-environment-64"></a>Environments can be thought of as consisting of two things. A <em>frame</em>, consisting of a set of symbol-value pairs, and an <em>enclosure</em>, a pointer to an enclosing environment. When R looks up the value for a symbol the frame is examined and if a matching symbol is found its value will be returned. If not, the enclosing environment is then accessed and the process repeated. Environments form a tree structure in which the enclosures play the role of parents. The tree of environments is rooted in an empty <a name="index-emptyenv-65"></a>environment, available through <code>emptyenv()</code>, which has no parent. It is the direct parent of the environment of the base package <a name="index-baseenv-66"></a>(available through the <code>baseenv()</code> function). Formerly <code>baseenv()</code> had the special value <code>NULL</code>, but as from version 2.4.0, the use of <code>NULL</code> as an environment is defunct. <p>Environments are created implicitly by function calls, as described in <a href="#Function-objects">Function objects</a> and <a href="#Lexical-environment">Lexical environment</a>. In this case the environment contains the variables local to the function (including the arguments), and its enclosure is the environment of the currently called function. Environments may also be created directly by <code>new.env</code>. <a name="index-new_002eenv-67"></a>The frame content of an environment can be accessed and manipulated by use of <code>ls</code>, <code>get</code> and <code>assign</code> as well as <code>eval</code> and <code>evalq</code>. <p>The <code>parent.env</code> function may be used to access the enclosure of an environment. <p>Unlike most other R objects, environments are not copied when passed to functions or used in assignments. Thus, if you assign the same environment to several symbols and change one, the others will change too. In particular, assigning attributes to an environment can lead to surprises. <div class="node"> <a name="Pairlist-objects"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Any_002dtype">Any-type</a>, Previous: <a rel="previous" accesskey="p" href="#Environment-objects">Environment objects</a>, Up: <a rel="up" accesskey="u" href="#Basic-types">Basic types</a> </div> <h4 class="subsection">2.1.11 Pairlist objects</h4> <p>Pairlist objects are similar to Lisp's dotted-pair lists. They are used extensively in the internals of R, but are rarely visible in interpreted code, although they are returned by <code>formals</code>, and can be created by (e.g.) the <code>pairlist</code> function. A zero-length pairlist is <code>NULL</code>, as would be expected in Lisp but in contrast to a zero-length list. <a name="index-pairlist-68"></a>Each such object has three slots, a CAR value, a CDR value and a TAG value. The TAG value is a text string and CAR and CDR usually represent, respectively, a list item (head) and the remainder (tail) of the list with a NULL object as terminator (the CAR/CDR terminology is traditional Lisp and originally referred to the address and decrement registers on an early 60's IBM computer). <!-- FIXME: Check: Is it *required* that TAG is a STRSXP and CDR is a --> <!-- LISTSXP?? (or NULL of course). --> <!-- Well, it is CHARSXP. --> <p>Pairlists are handled in the R language in exactly the same way as generic vectors (“lists”). In particular, elements are accessed using the same <code>[[]]</code> syntax. The use of pairlists is deprecated since generic vectors are usually more efficient to use. When an internal pairlist is accessed from R it is generally (including when subsetted) converted to a generic vector. <!-- FIXME: There are still exceptions. Change code or docs? --> <p>In a very few cases pairlists are user-visible: one is <code>.Options</code>. <div class="node"> <a name="Any-type"></a> <a name="Any_002dtype"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Pairlist-objects">Pairlist objects</a>, Up: <a rel="up" accesskey="u" href="#Basic-types">Basic types</a> </div> <h4 class="subsection">2.1.12 The “Any” type</h4> <p>It is not really possible for an object to be of “Any” type, but it is nevertheless a valid type value. It gets used in certain (rather rare) circumstances, e.g. <code>as.vector(x, "any")</code>, indicating that type <a name="index-coercion-69"></a>coercion should not be done. <!-- @node External pointer objects --> <!-- @subsection External pointer objects --> <div class="node"> <a name="Attributes"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Special-compound-objects">Special compound objects</a>, Previous: <a rel="previous" accesskey="p" href="#Basic-types">Basic types</a>, Up: <a rel="up" accesskey="u" href="#Objects">Objects</a> </div> <h3 class="section">2.2 Attributes</h3> <p><a name="index-attributes-70"></a> <a name="index-object-71"></a>All objects except <code>NULL</code> can have one or more attributes attached to them. Attributes are stored as a pairlist where all elements are named, but should be thought of as a set of name=value pairs. A listing of the attributes can be obtained using <code>attributes</code> and set by <code>attributes<-</code>, <a name="index-attributes-72"></a><a name="index-attributes_003c_002d-73"></a>individual components are accessed using <code>attr</code> and <code>attr<-</code>. <a name="index-attr-74"></a><a name="index-attr_003c_002d-75"></a><!-- Shouldn't we discuss replacement functions before this? --> <!-- This is a bad example: levels<- is generic. --> <p>Some attributes have special accessor <a name="index-function_002c-accessor-76"></a>functions (e.g. <code>levels<-</code> for factors) and these should be used when available. In addition to hiding details of implementation they may perform additional operations. R attempts to intercept calls to <code>attr<-</code> and to <code>attributes<-</code> that involve the special attributes and enforces the consistency checks. <p>Matrices and arrays are simply vectors with the attribute <code>dim</code> and optionally <code>dimnames</code> attached to the vector. <p>Attributes are used to implement the class structure used in R. If an object has a <code>class</code> attribute then that attribute will be examined during <a name="index-evaluation_002c-symbol-77"></a>evaluation. The class structure in R is described in detail in <a href="#Object_002doriented-programming">Object-oriented programming</a>. <ul class="menu"> <li><a accesskey="1" href="#Names">Names</a> <li><a accesskey="2" href="#Dimensions">Dimensions</a> <li><a accesskey="3" href="#Dimnames">Dimnames</a> <li><a accesskey="4" href="#Classes">Classes</a> <li><a accesskey="5" href="#Time-series-attributes">Time series attributes</a> <li><a accesskey="6" href="#Copying-of-attributes">Copying of attributes</a> </ul> <div class="node"> <a name="Names"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Dimensions">Dimensions</a>, Previous: <a rel="previous" accesskey="p" href="#Attributes">Attributes</a>, Up: <a rel="up" accesskey="u" href="#Attributes">Attributes</a> </div> <h4 class="subsection">2.2.1 Names</h4> <p>A <code>names</code> attribute, when present, labels the individual elements of a vector or list. When an object is printed the <code>names</code> attribute, when present, is used to label the elements. The <code>names</code> attribute can also be used for indexing purposes, for example, <code>quantile(x)["25%"]</code>. <p>One may get and set the names using <code>names</code> and <code>names<-</code> constructions. <a name="index-names-78"></a><a name="index-names_003c_002d-79"></a><a name="index-type-80"></a>The latter will perform the necessary consistency checks to ensure that the names attribute has the proper type and length. <p>Pairlists and one-dimensional arrays are treated specially. For pairlist objects, a virtual <code>names</code> attribute is used; the <code>names</code> attribute is really constructed from the tags of the list components. For one-dimensional arrays the <code>names</code> attribute really accesses <code>dimnames[[1]]</code>. <div class="node"> <a name="Dimensions"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Dimnames">Dimnames</a>, Previous: <a rel="previous" accesskey="p" href="#Names">Names</a>, Up: <a rel="up" accesskey="u" href="#Attributes">Attributes</a> </div> <h4 class="subsection">2.2.2 Dimensions</h4> <p>The <code>dim</code> attribute is used to implement arrays. The content of the array is stored in a vector in column-major order and the <code>dim</code> attribute is a vector of integers specifying the respective extents of the array. R ensures that the length of the vector is the product of the lengths of the dimensions. The length of one or more dimensions may be zero. <p><a name="index-vector-81"></a>A vector is not the same as a one-dimensional array since the latter has a <code>dim</code> attribute of length one, whereas the former has no <code>dim</code> attribute. <div class="node"> <a name="Dimnames"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Classes">Classes</a>, Previous: <a rel="previous" accesskey="p" href="#Dimensions">Dimensions</a>, Up: <a rel="up" accesskey="u" href="#Attributes">Attributes</a> </div> <h4 class="subsection">2.2.3 Dimnames</h4> <p>Arrays may name each dimension separately using the <code>dimnames</code> attribute which is a list of character vectors. The <code>dimnames</code> list may itself have names which are then used for extent headings when printing arrays. <div class="node"> <a name="Classes"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Time-series-attributes">Time series attributes</a>, Previous: <a rel="previous" accesskey="p" href="#Dimnames">Dimnames</a>, Up: <a rel="up" accesskey="u" href="#Attributes">Attributes</a> </div> <h4 class="subsection">2.2.4 Classes</h4> <p>R has an elaborate class system<a rel="footnote" href="#fn-1" name="fnd-1"><sup>1</sup></a>, principally controlled via the <code>class</code> attribute. This attribute is a character vector containing the list of classes that an object inherits from. This forms the basis of the “generic methods” functionality in R. <p>This attribute can be accessed and manipulated virtually without restriction by users. There is no checking that an object actually contains the components that class methods expect. Thus, altering the <code>class</code> attribute should be done with caution, and when they are available specific creation and <a name="index-coercion-82"></a>coercion functions should be preferred. <div class="node"> <a name="Time-series-attributes"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Copying-of-attributes">Copying of attributes</a>, Previous: <a rel="previous" accesskey="p" href="#Classes">Classes</a>, Up: <a rel="up" accesskey="u" href="#Attributes">Attributes</a> </div> <h4 class="subsection">2.2.5 Time series attributes</h4> <p>The <code>tsp</code> attribute is used to hold parameters of time series, start, end, and frequency. This construction is mainly used to handle series with periodic substructure such as monthly or quarterly data. <div class="node"> <a name="Copying-of-attributes"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Time-series-attributes">Time series attributes</a>, Up: <a rel="up" accesskey="u" href="#Attributes">Attributes</a> </div> <h4 class="subsection">2.2.6 Copying of attributes</h4> <p>Whether attributes should be copied when an object is altered is a complex area, but there are some general rules (Becker, Chambers & Wilks, 1988, pp. 144–6). <p>Scalar functions (those which operate element-by-element on a vector and whose output is similar to the input) should preserve attributes (except perhaps class). <p>Binary operations normally copy most attributes from the longer argument (and if they are of the same length from both, preferring the values on the first). Here ‘most’ means all except the <code>names</code>, <code>dim</code> and <code>dimnames</code> which are set appropriately by the code for the operator. <p>Subsetting (other than by an empty index) generally drops all attributes except <code>names</code>, <code>dim</code> and <code>dimnames</code> which are reset as appropriate. On the other hand, subassignment generally preserves attributes even if the length is changed. Coercion drops all attributes. <p>The default method for sorting drops all attributes except names, which are sorted along with the object. <div class="node"> <a name="Special-compound-objects"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Attributes">Attributes</a>, Up: <a rel="up" accesskey="u" href="#Objects">Objects</a> </div> <h3 class="section">2.3 Special compound objects</h3> <ul class="menu"> <li><a accesskey="1" href="#Factors">Factors</a> <li><a accesskey="2" href="#Data-frame-objects">Data frame objects</a> </ul> <div class="node"> <a name="Factors"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Data-frame-objects">Data frame objects</a>, Previous: <a rel="previous" accesskey="p" href="#Special-compound-objects">Special compound objects</a>, Up: <a rel="up" accesskey="u" href="#Special-compound-objects">Special compound objects</a> </div> <h4 class="subsection">2.3.1 Factors</h4> <p>Factors are used to describe items that can have a finite number of values (gender, social class, etc.). A factor has a <code>levels</code> attribute and class <code>"factor"</code>. Optionally, it may also contain a <code>contrasts</code> attribute which controls the parametrisation used when the factor is used in a <a name="index-function_002c-modeling-83"></a><a name="index-modeling-function-84"></a>modeling functions. <p>A factor may be purely nominal or may have ordered categories. In the latter case, it should be defined as such and have a <code>class</code> vector <code>c("ordered"," factor")</code>. <p>Factors are currently implemented using an integer array to specify the actual levels and a second array of names that are mapped to the integers. Rather unfortunately users often make use of the implementation in order to make some calculations easier. This, however, is an implementation issue and is not guaranteed to hold in all implementations of R. <div class="node"> <a name="Data-frame-objects"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Factors">Factors</a>, Up: <a rel="up" accesskey="u" href="#Special-compound-objects">Special compound objects</a> </div> <h4 class="subsection">2.3.2 Data frame objects</h4> <p>Data frames are the R structures which most closely mimic the SAS or SPSS data set, i.e. a “cases by variables” matrix of data. <p>A data frame is a list of vectors, factors, and/or matrices all having the same length (number of rows in the case of matrices). In addition, a data frame generally has a <code>names</code> attribute labeling the variables and a <code>row.names</code> attribute for labeling the cases. <p>A data frame can contain a list that is the same length as the other components. The list can contain elements of differing lengths thereby providing a data structure for ragged arrays. However, as of this writing such arrays are not generally handled correctly. <!-- FIXME: these details really need to be filled in --> <!-- @node Type checking and coercion, , Special compound objects, Objects --> <!-- @section Type checking and coercion --> <!-- For most of the basic data types we can check the type and coerce --> <!-- objects of one type to another type. Should we have a table??? --> <!-- @menu --> <!-- * mode/typeof:: --> <!-- * Specific types:: --> <!-- * Metatypes:: --> <!-- @end menu --> <!-- @node mode/typeof, Specific types, Type checking and coercion, Type checking and coercion --> <!-- @subsection mode/typeof --> <!-- @node Specific types, Metatypes, mode/typeof, Type checking and coercion --> <!-- @subsection Specific types --> <!-- @node Metatypes, , Specific types, Type checking and coercion --> <!-- @subsection Metatypes --> <!-- @findex is.numeric --> <!-- @findex is.finite --> <!-- --> <!-- @node Data structures, Evaluation of expressions, Objects, Top --> <!-- @chapter Data structures --> <!-- @menu --> <!-- * Vectors:: --> <!-- * Lists:: --> <!-- * Arrays:: --> <!-- * Matrices:: --> <!-- * Assignment:: --> <!-- * Matrix operations:: --> <!-- * Data Frames:: --> <!-- @end menu --> <!-- @node Vectors, Lists, Data structures, Data structures --> <!-- @section Vectors --> <!-- @node Lists, Arrays, Vectors, Data structures --> <!-- @section Lists --> <!-- @node Arrays, Matrices, Lists, Data structures --> <!-- @section Arrays --> <!-- @node Matrices, Assignment, Arrays, Data structures --> <!-- @section Matrices --> <!-- @node Assignment, Matrix operations, Matrices, Data structures --> <!-- @section Assignment --> <!-- @menu --> <!-- * simple:: --> <!-- * indexed:: --> <!-- * function:: --> <!-- @end menu --> <!-- @node simple, indexed, Assignment, Assignment --> <!-- @subsection simple --> <!-- @node indexed, function, simple, Assignment --> <!-- @subsection indexed --> <!-- @node function, , indexed, Assignment --> <!-- @subsection function --> <!-- @node Matrix operations, Data Frames, Assignment, Data structures --> <!-- @section Matrix operations --> <!-- @node Data Frames, , Matrix operations, Data structures --> <!-- @section Data Frames --> <div class="node"> <a name="Evaluation-of-expressions"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Functions">Functions</a>, Previous: <a rel="previous" accesskey="p" href="#Objects">Objects</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <!-- node-name, next, previous, up --> <h2 class="chapter">3 Evaluation of expressions</h2> <p>When a user types a command at the prompt (or when an expression is read from a file) the first thing that happens to it is that the command is transformed by the <a name="index-parsing-85"></a>parser into an internal representation. The evaluator executes parsed R expressions and returns the value of the expression. All expressions have a value. This is the core of the language. <p>This chapter describes the basic mechanisms of the evaluator, but avoids discussion of specific functions or groups of functions which are described in separate chapters later on or where the help pages should be sufficient documentation. <p>Users can construct expressions and invoke the evaluator on them. <ul class="menu"> <li><a accesskey="1" href="#Simple-evaluation">Simple evaluation</a> <li><a accesskey="2" href="#Control-structures">Control structures</a> <li><a accesskey="3" href="#Elementary-arithmetic-operations">Elementary arithmetic operations</a> <li><a accesskey="4" href="#Indexing">Indexing</a> <li><a accesskey="5" href="#Scope-of-variables">Scope of variables</a> </ul> <div class="node"> <a name="Simple-evaluation"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Control-structures">Control structures</a>, Previous: <a rel="previous" accesskey="p" href="#Evaluation-of-expressions">Evaluation of expressions</a>, Up: <a rel="up" accesskey="u" href="#Evaluation-of-expressions">Evaluation of expressions</a> </div> <h3 class="section">3.1 Simple evaluation</h3> <ul class="menu"> <li><a accesskey="1" href="#Constants">Constants</a> <li><a accesskey="2" href="#Symbol-lookup">Symbol lookup</a> <li><a accesskey="3" href="#Function-calls">Function calls</a> <li><a accesskey="4" href="#Operators">Operators</a> </ul> <div class="node"> <a name="Constants"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Symbol-lookup">Symbol lookup</a>, Previous: <a rel="previous" accesskey="p" href="#Simple-evaluation">Simple evaluation</a>, Up: <a rel="up" accesskey="u" href="#Simple-evaluation">Simple evaluation</a> </div> <h4 class="subsection">3.1.1 Constants</h4> <p>Any number typed directly at the prompt is a constant and is evaluated. <pre class="example"> > 1 [1] 1 </pre> <p class="noindent">Perhaps unexpectedly, the number returned from the expression <code>1</code> is a numeric. In most cases, the difference between an integer and a numeric value will be unimportant as R will do the right thing when using the numbers. There are, however, times when we would like to explicitly create an integer value for a constant. We can do this by calling the function <code>as.integer</code> or using various other techniques. But perhaps the simplest approach is to qualify our constant with the suffix character ‘L’. For example, to create the integer value 1, we might use <pre class="example"> > 1L [1] </pre> <p>We can use the ‘L’ suffix to qualify any number with the intent of making it an explicit integer. So ‘0x10L’ creates the integer value 16 from the hexadecimal representation. The constant <code>1e3L</code> gives 1000 as an integer rather than a numeric value and is equivalent to <code>1000L</code>. (Note that the ‘L’ is treated as qualifying the term <code>1e3</code> and not the <code>3</code>.) If we qualify a value with ‘L’ that is not an integer value, e.g. <code>1e-3L</code>, we get a warning and the numeric value is created. A warning is also created if there is an unnecessary decimal point in the number, e.g. <code>1.L</code>. <p>We get a syntax error when using ‘L’ with complex numbers, e.g. <code>12iL</code> gives an error. <p>Constants are fairly boring and to do more we need symbols. <div class="node"> <a name="Symbol-lookup"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Function-calls">Function calls</a>, Previous: <a rel="previous" accesskey="p" href="#Constants">Constants</a>, Up: <a rel="up" accesskey="u" href="#Simple-evaluation">Simple evaluation</a> </div> <h4 class="subsection">3.1.2 Symbol lookup</h4> <p>When a new variable is created it must have a <a name="index-name-86"></a>name so it can be referenced and it usually has a value. The name itself is a <a name="index-symbol-87"></a>symbol. When a symbol is <a name="index-evaluation_002c-symbol-88"></a>evaluated its <a name="index-value-89"></a>value is returned. Later we shall explain in detail how to determine the value associated with a symbol. <p>In this small example <code>y</code> is a symbol and its value is 4. A symbol is an R object too, but one rarely needs to deal with symbols directly, except when doing “programming on the language” (<a href="#Computing-on-the-language">Computing on the language</a>). <pre class="example"> > y <- 4 > y [1] 4 </pre> <!-- FIXME: Probably needs to go somewhere, but not here (parser section?) --> <!-- FIXME: Up to date info is in the subsection ‘Reserved words’. --> <!-- @node Key words, Calling functions, Symbol lookup, Simple evaluation --> <!-- @subsection Key words --> <!-- @R{} contains a number of key words. These are symbols that the parser --> <!-- treats in a special fashion. They are, --> <!-- @quotation --> <!-- @multitable @columnfractions 0.2 0.7 --> <!-- @item @code{NULL} @tab the null object --> <!-- @item @code{NA} @tab missing value --> <!-- @item @code{TRUE} @tab logical true --> <!-- @item @code{FALSE} @tab logical false --> <!-- @item @code{Inf} @tab infinity --> <!-- @item @code{NaN} @tab not a number --> <!-- @item @code{function} @tab a special form for creating functions --> <!-- @item @code{while} @tab while flow control --> <!-- @item @code{repeat} @tab repeat flow control --> <!-- @item @code{for} @tab for flow control --> <!-- @item @code{if} @tab if-then-else statements --> <!-- @item @code{in} @tab used in flow control --> <!-- @item @code{else} @tab part of the if-then-else construct --> <!-- @item @code{next} @tab flow control --> <!-- @item @code{break} @tab flow control --> <!-- @item @code{...} @tab special argument for functions --> <!-- @end multitable --> <!-- @end quotation --> <div class="node"> <a name="Function-calls"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Operators">Operators</a>, Previous: <a rel="previous" accesskey="p" href="#Symbol-lookup">Symbol lookup</a>, Up: <a rel="up" accesskey="u" href="#Simple-evaluation">Simple evaluation</a> </div> <h4 class="subsection">3.1.3 Function calls</h4> <p>Most of the computations carried out in R involve the evaluation of functions. We will also refer to this as <a name="index-function-invocation-90"></a>function <em>invocation</em>. Functions are invoked by name with a list of arguments separated by commas. <pre class="example"> > mean(1:10) [1] 5.5 </pre> <p class="noindent">In this example the function <code>mean</code> was called with one argument, the vector of integers from 1 to 10. <p>R contains a huge number of functions with different purposes. Most are used for producing a result which is an R object, but others are used for their side effects, e.g., printing and plotting functions. <p><a name="index-function-91"></a><a name="index-function-arguments-92"></a>Function calls can have <em>tagged</em> (or <em>named</em>) arguments, as in <code>plot(x, y, pch = 3)</code> arguments without tags are known as <em>positional</em> since the function must distinguish their meaning from their sequential positions among the arguments of the call, e.g., that <code>x</code> denotes the abscissa variable and <code>y</code> the ordinate. The use of tags/names is an obvious convenience for functions with a large number of optional arguments. <p><a name="index-function_002c-assignment-93"></a>A special type of function calls can appear on the left hand side of the <a name="index-assignment-94"></a>assignment operator as in <pre class="example"> > class(x) <- "foo" </pre> <p class="noindent">What this construction really does is to call the function <code>class<-</code> with the original object and the right hand side. This function performs the modification of the object and returns the result which is then stored back into the original variable. (At least conceptually, this is what happens. Some additional effort is made to avoid unnecessary data duplication.) <!-- FIXME something about common constructor functions: c, --> <!-- array, matrix, list, structure (with a warning to use the --> <!-- latter with discretion), --> <div class="node"> <a name="Operators"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Function-calls">Function calls</a>, Up: <a rel="up" accesskey="u" href="#Simple-evaluation">Simple evaluation</a> </div> <h4 class="subsection">3.1.4 Operators</h4> <p>R allows the use of arithmetic expressions using operators similar to those of the C programming language, for instance <pre class="example"> > 1 + 2 [1] 3 </pre> <p>Expressions can be grouped using parentheses, mixed with function calls, and assigned to variables in a straightforward manner <pre class="example"> > y <- 2 * (a + log(x)) </pre> <p>R contains a number of operators. They are listed in the table below. <blockquote> <p><table summary=""><tr align="left"><td valign="top" width="10%"><code>-</code> </td><td valign="top" width="70%">Minus, can be unary or binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>+</code> </td><td valign="top" width="70%">Plus, can be unary or binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>!</code> </td><td valign="top" width="70%">Unary not <br></td></tr><tr align="left"><td valign="top" width="10%"><code>~</code> </td><td valign="top" width="70%">Tilde, used for model formulae, can be either unary or binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>?</code> </td><td valign="top" width="70%">Help <br></td></tr><tr align="left"><td valign="top" width="10%"><code>:</code> </td><td valign="top" width="70%">Sequence, binary (in model formulae: interaction) <br></td></tr><tr align="left"><td valign="top" width="10%"><code>*</code> </td><td valign="top" width="70%">Multiplication, binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>/</code> </td><td valign="top" width="70%">Division, binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>^</code> </td><td valign="top" width="70%">Exponentiation, binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>%</code><var>x</var><code>%</code> </td><td valign="top" width="70%">Special binary operators, <var>x</var> can be replaced by any valid name <br></td></tr><tr align="left"><td valign="top" width="10%"><code>%%</code> </td><td valign="top" width="70%">Modulus, binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>%/%</code> </td><td valign="top" width="70%">Integer divide, binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>%*%</code> </td><td valign="top" width="70%">Matrix product, binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>%o%</code> </td><td valign="top" width="70%">Outer product, binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>%x%</code> </td><td valign="top" width="70%">Kronecker product, binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>%in%</code> </td><td valign="top" width="70%">Matching operator, binary (in model formulae: nesting) <br></td></tr><tr align="left"><td valign="top" width="10%"><code><</code> </td><td valign="top" width="70%">Less than, binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>></code> </td><td valign="top" width="70%">Greater than, binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>==</code> </td><td valign="top" width="70%">Equal to, binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>>=</code> </td><td valign="top" width="70%">Greater than or equal to, binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code><=</code> </td><td valign="top" width="70%">Less than or equal to, binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>&</code> </td><td valign="top" width="70%">And, binary, vectorized <br></td></tr><tr align="left"><td valign="top" width="10%"><code>&&</code> </td><td valign="top" width="70%">And, binary, not vectorized <br></td></tr><tr align="left"><td valign="top" width="10%"><code>|</code> </td><td valign="top" width="70%">Or, binary, vectorized <br></td></tr><tr align="left"><td valign="top" width="10%"><code>||</code> </td><td valign="top" width="70%">Or, binary, not vectorized <br></td></tr><tr align="left"><td valign="top" width="10%"><code><-</code> </td><td valign="top" width="70%">Left assignment, binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>-></code> </td><td valign="top" width="70%">Right assignment, binary <br></td></tr><tr align="left"><td valign="top" width="10%"><code>$</code> </td><td valign="top" width="70%">List subset, binary <br></td></tr></table> </blockquote> <p>Except for the syntax, there is no difference between applying an operator and calling a function. In fact, <code>x + y</code> can equivalently be written <code>`+`(x, y)</code>. Notice that since ‘<samp><span class="samp">+</span></samp>’ is a non-standard function name, it needs to be quoted. <p><a name="index-vector-95"></a>R deals with entire vectors of data at a time, and most of the elementary operators and basic mathematical functions like <code>log</code> are vectorized (as indicated in the table above). This means that e.g. adding two vectors of the same length will create a vector containing the element-wise sums, implicitly looping over the vector index. This applies also to other operators like <code>-</code>, <code>*</code>, and <code>/</code> as well as to higher dimensional structures. Notice in particular that multiplying two matrices does not produce the usual matrix product (the <code>%*%</code> operator exists for that purpose). Some finer points relating to vectorized operations will be discussed in <a href="#Elementary-arithmetic-operations">Elementary arithmetic operations</a>. <!-- FIXME insert reference --> <p>To access individual elements of an atomic vector, one generally uses the <code>x[i]</code> construction. <pre class="example"> > x <- rnorm(5) > x [1] -0.12526937 -0.27961154 -1.03718717 -0.08156527 1.37167090 > x[2] [1] -0.2796115 </pre> <p>List components are more commonly accessed using <code>x$a</code> or <code>x[[i]]</code>. <pre class="example"> > x <- options() > x$prompt [1] "> " </pre> <p>Indexing constructs can also appear on the right hand side of an <a name="index-assignment-96"></a>assignment. <p>Like the other operators, indexing is really done by functions, and one could have used <code>`[`(x, 2)</code> instead of <code>x[2]</code>. <p>R's indexing operations contain many advanced features which are further described in <a href="#Indexing">Indexing</a>. <div class="node"> <a name="Control-structures"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Elementary-arithmetic-operations">Elementary arithmetic operations</a>, Previous: <a rel="previous" accesskey="p" href="#Simple-evaluation">Simple evaluation</a>, Up: <a rel="up" accesskey="u" href="#Evaluation-of-expressions">Evaluation of expressions</a> </div> <h3 class="section">3.2 Control structures</h3> <p>Computation in R consists of sequentially evaluating <em>statements</em>. Statements, such as <code>x<-1:10</code> or <code>mean(y)</code>, can be separated by either a semi-colon or a new line. Whenever the <a name="index-evaluation_002c-statement-97"></a>evaluator is presented with a syntactically complete statement that statement is evaluated and the <em>value</em> returned. The result of evaluating a statement can be referred to as the value of the statement<a rel="footnote" href="#fn-2" name="fnd-2"><sup>2</sup></a> The value can always be assigned to a symbol. <p>Both semicolons and new lines can be used to separate statements. A semicolon always indicates the end of a statement while a new line <em>may</em> indicate the end of a statement. If the current statement is not syntactically complete new lines are simply ignored by the evaluator. If the session is interactive the prompt changes from ‘<samp><span class="samp">></span></samp>’ to ‘<samp><span class="samp">+</span></samp>’. <pre class="example"> > x <- 0; x + 5 [1] 5 > y <- 1:10 > 1; 2 [1] 1 [1] 2 </pre> <p>Statements can be grouped together using braces ‘<samp><span class="samp">{</span></samp>’ and ‘<samp><span class="samp">}</span></samp>’. A group of statements is sometimes called a <em>block</em>. Single statements are evaluated when a new line is typed at the end of the syntactically complete statement. Blocks are not evaluated until a new line is entered after the closing brace. In the remainder of this section, <em>statement</em> refers to either a single statement or a block. <pre class="example"> > { x <- 0 + x + 5 + } [1] 5 </pre> <ul class="menu"> <li><a accesskey="1" href="#if">if</a> <li><a accesskey="2" href="#Looping">Looping</a> <li><a accesskey="3" href="#repeat">repeat</a> <li><a accesskey="4" href="#while">while</a> <li><a accesskey="5" href="#for">for</a> <li><a accesskey="6" href="#switch">switch</a> </ul> <div class="node"> <a name="if"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Looping">Looping</a>, Previous: <a rel="previous" accesskey="p" href="#Control-structures">Control structures</a>, Up: <a rel="up" accesskey="u" href="#Control-structures">Control structures</a> </div> <h4 class="subsection">3.2.1 if</h4> <p>The <code>if</code>/<code>else</code> statement conditionally evaluates two statements. There is a <em>condition</em> which is evaluated and if the <em>value</em> is <code>TRUE</code> then the first statement is evaluated; otherwise the second statement will be evaluated. The <code>if</code>/<code>else</code> statement returns, as its value, the value of the statement that was selected. The formal syntax is <pre class="example"> if ( <var>statement1</var> ) <var>statement2</var> else <var>statement3</var> </pre> <p>First, <var>statement1</var> is evaluated to yield <var>value1</var>. If <var>value1</var> is a logical vector with first element <code>TRUE</code> then <var>statement2</var> is evaluated. If the first element of <var>value1</var> is <code>FALSE</code> then <var>statement3</var> is evaluated. If <var>value1</var> is a numeric vector then <var>statement3</var> is evaluated when the first element of <var>value1</var> is zero and otherwise <var>statement2</var> is evaluated. Only the first element of <var>value1</var> is used. All other elements are ignored. If <var>value1</var> has any type other than a logical or a numeric vector an error is signalled. <p>If/else statements can be used to avoid numeric problems such as taking the logarithm of a negative number. Because if/else statements are the same as other statements you can assign the value of them. The two examples below are equivalent. <pre class="example"> > if( any(x <= 0) ) y <- log(1+x) else y <- log(x) > y <- if( any(x <= 0) ) log(1+x) else log(x) </pre> <p>The <code>else</code> clause is optional. The statement <code>if(any(x <= 0)) x <- x[x <= 0]</code> is valid. When the <code>if</code> statement is not in a block the <code>else</code>, if present, must appear on the same line as the end of <var>statement2</var>. Otherwise the new line at the end of <var>statement2</var> completes the <code>if</code> and yields a syntactically complete statement that is evaluated. A simple solution is to use a compound statement wrapped in braces, putting the <code>else</code> on the same line as the closing brace that marks the end of the statement. <p>If/else statements can be nested. <pre class="example"> if ( <var>statement1</var> ) { <var>statement2</var> } else if ( <var>statement3</var> ) { <var>statement4</var> } else if ( <var>statement5</var> ) { <var>statement6</var> } else <var>statement8</var> </pre> <p>One of the even numbered statements will be evaluated and the resulting value returned. If the optional <code>else</code> clause is omitted and all the odd numbered <var>statement</var>'s evaluate to <code>FALSE</code> no statement will be evaluated and <code>NULL</code> is returned. <p>The odd numbered <var>statement</var>s are evaluated, in order, until one evaluates to <code>TRUE</code> and then the associated even numbered <var>statement</var> is evaluated. In this example, <var>statement6</var> will only be evaluated if <var>statement1</var> is <code>FALSE</code> and <var>statement3</var> is <code>FALSE</code> and <var>statement5</var> is <code>TRUE</code>. There is no limit to the number of <code>else if</code> clauses that are permitted. <div class="node"> <a name="Looping"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#repeat">repeat</a>, Previous: <a rel="previous" accesskey="p" href="#if">if</a>, Up: <a rel="up" accesskey="u" href="#Control-structures">Control structures</a> </div> <h4 class="subsection">3.2.2 Looping</h4> <p>R has three statements that provide explicit looping.<a rel="footnote" href="#fn-3" name="fnd-3"><sup>3</sup></a> They are <code>for</code>, <code>while</code> and <code>repeat</code>. The two built-in constructs, <code>next</code> and <code>break</code>, provide additional control over the evaluation. Each of the three statements returns the value of the last statement that was evaluated. It is possible, although uncommon, to assign the result of one of these statements to a symbol. R provides other functions for implicit looping such as <code>tapply</code>, <code>apply</code>, and <code>lapply</code>. In addition many operations, especially arithmetic ones, are vectorized so you may not need to use a loop. <p>There are two statements that can be used to explicitly control looping. They are <code>break</code> and <code>next</code>. <a name="index-break-98"></a><a name="index-next-99"></a>The <code>break</code> statement causes an exit from the innermost loop that is currently being executed. The <code>next</code> statement immediately causes control to return to the start of the loop. The next iteration of the loop (if there is one) is then executed. No statement below <code>next</code> in the current loop is evaluated. <p>The value returned by a loop statement statement is always <code>NULL</code> and is returned invisibly. <div class="node"> <a name="repeat"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#while">while</a>, Previous: <a rel="previous" accesskey="p" href="#Looping">Looping</a>, Up: <a rel="up" accesskey="u" href="#Control-structures">Control structures</a> </div> <h4 class="subsection">3.2.3 repeat</h4> <p><a name="index-repeat-100"></a> The <code>repeat</code> statement causes repeated evaluation of the body until a break is specifically requested. This means that you need to be careful when using <code>repeat</code> because of the danger of an infinite loop. The syntax of the <code>repeat</code> loop is <pre class="example"> repeat <var>statement</var> </pre> <p>When using <code>repeat</code>, <var>statement</var> must be a block statement. You need to both perform some computation and test whether or not to break from the loop and usually this requires two statements. <div class="node"> <a name="while"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#for">for</a>, Previous: <a rel="previous" accesskey="p" href="#repeat">repeat</a>, Up: <a rel="up" accesskey="u" href="#Control-structures">Control structures</a> </div> <h4 class="subsection">3.2.4 while</h4> <p><a name="index-while-101"></a> The <code>while</code> statement is very similar to the <code>repeat</code> statement. The syntax of the <code>while</code> loop is <pre class="example"> while ( <var>statement1</var> ) <var>statement2</var> </pre> <p class="noindent">where <var>statement1</var> is evaluated and if its value is <code>TRUE</code> then <var>statement2</var> is evaluated. This process continues until <var>statement1</var> evaluates to <code>FALSE</code>. <div class="node"> <a name="for"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#switch">switch</a>, Previous: <a rel="previous" accesskey="p" href="#while">while</a>, Up: <a rel="up" accesskey="u" href="#Control-structures">Control structures</a> </div> <h4 class="subsection">3.2.5 for</h4> <p><a name="index-for-102"></a> The syntax of the <code>for</code> loop is <pre class="example"> for ( <var>name</var> in <var>vector</var> ) <var>statement1</var> </pre> <p class="noindent">where <var>vector</var> can be either a vector or a list. For each element in <var>vector</var> the variable <var>name</var> is set to the value of that element and <var>statement1</var> is evaluated. A side effect is that the variable <var>name</var> still exists after the loop has concluded and it has the value of the last element of <var>vector</var> that the loop was evaluated for. <div class="node"> <a name="switch"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#for">for</a>, Up: <a rel="up" accesskey="u" href="#Control-structures">Control structures</a> </div> <h4 class="subsection">3.2.6 switch</h4> <p><a name="index-switch-103"></a> Technically speaking, <code>switch</code> is just another function, but its semantics are close to those of control structures of other programming languages. <p>The syntax is <pre class="example"> switch (<var>statement</var>, <var>list</var>) </pre> <p class="noindent">where the elements of <var>list</var> may be named. First, <var>statement</var> is evaluated and the result, <var>value</var>, obtained. If <var>value</var> is a number between 1 and the length of <var>list</var> then the corresponding element <var>list</var> is evaluated and the result returned. If <var>value</var> is too large or too small <code>NULL</code> is returned. <pre class="example"> > x <- 3 > switch(x, 2+2, mean(1:10), rnorm(5)) [1] 2.2903605 2.3271663 -0.7060073 1.3622045 -0.2892720 > switch(2, 2+2, mean(1:10), rnorm(5)) [1] 5.5 > switch(6, 2+2, mean(1:10), rnorm(5)) NULL </pre> <p>If <var>value</var> is a character vector then the element of ‘<samp><span class="samp">...</span></samp>’ with a name that exactly matches <var>value</var> is evaluated. If there is no match a single unnamed argument will be used as a default. If no default is specified, <code>NULL</code> is returned. <pre class="example"> > y <- "fruit" > switch(y, fruit = "banana", vegetable = "broccoli", "Neither") [1] "banana" > y <- "meat" > switch(y, fruit = "banana", vegetable = "broccoli", "Neither") [1] "Neither" </pre> <p>A common use of <code>switch</code> is to branch according to the character value of one of the arguments to a function. <pre class="example"> > centre <- function(x, type) { + switch(type, + mean = mean(x), + median = median(x), + trimmed = mean(x, trim = .1)) + } > x <- rcauchy(10) > centre(x, "mean") [1] 0.8760325 > centre(x, "median") [1] 0.5360891 > centre(x, "trimmed") [1] 0.6086504 </pre> <p><code>switch</code> returns either the value of the statement that was evaluated or <code>NULL</code> if no statement was evaluated. <p>To choose from a list of alternatives that already exists <code>switch</code> may not be the best way to select one for evaluation. It is often better to use <code>eval</code> and the subset operator, <code>[[</code>, directly via <code>eval(x[[condition]])</code>. <div class="node"> <a name="Elementary-arithmetic-operations"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Indexing">Indexing</a>, Previous: <a rel="previous" accesskey="p" href="#Control-structures">Control structures</a>, Up: <a rel="up" accesskey="u" href="#Evaluation-of-expressions">Evaluation of expressions</a> </div> <h3 class="section">3.3 Elementary arithmetic operations</h3> <ul class="menu"> <li><a accesskey="1" href="#Recycling-rules">Recycling rules</a> <li><a accesskey="2" href="#Propagation-of-names">Propagation of names</a> <li><a accesskey="3" href="#Dimensional-attributes">Dimensional attributes</a> <li><a accesskey="4" href="#NA-handling">NA handling</a> </ul> <p>In this section, we discuss the finer points of the rules that apply to basic operation like addition or multiplication of two vectors or matrices. <div class="node"> <a name="Recycling-rules"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Propagation-of-names">Propagation of names</a>, Previous: <a rel="previous" accesskey="p" href="#Elementary-arithmetic-operations">Elementary arithmetic operations</a>, Up: <a rel="up" accesskey="u" href="#Elementary-arithmetic-operations">Elementary arithmetic operations</a> </div> <h4 class="subsection">3.3.1 Recycling rules</h4> <p>If one tries to add two structures with a different number of elements, then the shortest is recycled to length of longest. That is, if for instance you add <code>c(1, 2, 3)</code> to a six-element vector then you will really add <code>c(1, 2, 3, 1, 2, 3)</code>. If the length of the longer vector is not a multiple of the shorter one, a warning is given. <p>As from R 1.4.0, any arithmetic operation involving a zero-length vector has a zero-length result. <p>One exception is that when adding vectors to matrices, a warning is not given if the lengths are incompatible. <!-- Is that a bug? --> <div class="node"> <a name="Propagation-of-names"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Dimensional-attributes">Dimensional attributes</a>, Previous: <a rel="previous" accesskey="p" href="#Recycling-rules">Recycling rules</a>, Up: <a rel="up" accesskey="u" href="#Elementary-arithmetic-operations">Elementary arithmetic operations</a> </div> <h4 class="subsection">3.3.2 Propagation of names</h4> <p><a name="index-name-104"></a>propagation of names (first one wins, I think - also if it has no names?? —– first one *with names* wins, recycling causes shortest to lose names) <div class="node"> <a name="Dimensional-attributes"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#NA-handling">NA handling</a>, Previous: <a rel="previous" accesskey="p" href="#Propagation-of-names">Propagation of names</a>, Up: <a rel="up" accesskey="u" href="#Elementary-arithmetic-operations">Elementary arithmetic operations</a> </div> <h4 class="subsection">3.3.3 Dimensional attributes</h4> <p>(matrix+matrix, dimensions must match. vector+matrix: first recycle, then check if dims fit, error if not) <div class="node"> <a name="NA-handling"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Dimensional-attributes">Dimensional attributes</a>, Up: <a rel="up" accesskey="u" href="#Elementary-arithmetic-operations">Elementary arithmetic operations</a> </div> <h4 class="subsection">3.3.4 NA handling</h4> <p>Missing values in the statistical sense, that is, variables whose value is not known, have the value <code>NA</code>. This should not be confused with the <code>missing</code> property for a function argument that has not been supplied (see <a href="#Arguments">Arguments</a>). <a name="index-missing-105"></a><a name="index-NA-106"></a><a name="index-NaN-107"></a> <a name="index-type-108"></a>As the elements of an atomic vector must be of the same type there are multiple types of <code>NA</code> values. There is one case where this is particularly important to the user. The default type of <code>NA</code> is <code>logical</code>, unless coerced to some other type, so the appearance of a missing value may trigger logical rather than numeric indexing (see <a href="#Indexing">Indexing</a> for details). <p>Numeric and logical calculations with <code>NA</code> generally return <code>NA</code>. In cases where the result of the operation would be the same for all possible values the <code>NA</code> could take, the operation may return this value. In particular, ‘<samp><span class="samp">FALSE & NA</span></samp>’ is <code>FALSE</code>, ‘<samp><span class="samp">TRUE | NA</span></samp>’ is <code>TRUE</code>. <code>NA</code> is not equal to any other value or to itself; testing for <code>NA</code> is done using <code>is.na</code>. <a name="index-is_002ena-109"></a>However, an <code>NA</code> value will match another <code>NA</code> value in <code>match</code>. <p>Numeric calculations whose result is undefined, such as ‘<samp><span class="samp">0/0</span></samp>’, produce the value <code>NaN</code>. This exists only in the <code>double</code> type and for real or imaginary components of the complex type. The function <code>is.nan</code> is provided to check specifically for <a name="index-is_002enan-110"></a><code>NaN</code>, <code>is.na</code> also returns <code>TRUE</code> for <code>NaN</code>. <a name="index-coercion-111"></a>Coercing <code>NaN</code> to logical or integer type gives an <code>NA</code> of the appropriate type, but coercion to character gives the string <code>"NaN"</code>. <code>NaN</code> values are incomparable so tests of equality or collation involving <code>NaN</code> will result in <code>NA</code>. They are regarded as matching any <code>NaN</code> value (and no other value, not even <code>NA</code>) by <code>match</code>. <p>The <code>NA</code> of character type is as from R 1.5.0 distinct from the string <code>"NA"</code>. Programmers who need to specify an explicit string <code>NA</code> should use ‘<samp><span class="samp">as.character(NA)</span></samp>’ rather than <code>"NA"</code>, or set elements to <code>NA</code> using <code>is.na<-</code>. <p>As from R 2.5.0 there are constants <code>NA_integer_</code>, <code>NA_real_</code>, <code>NA_complex_</code> and <code>NA_character_</code> which will generate (in the parser) an <code>NA</code> value of the appropriate type, and will be used in deparsing when it is not otherwise possible to identify the type of an <code>NA</code> (and the <code>control</code> options ask for this to be done). <p>There is no <code>NA</code> value for raw vectors. <div class="node"> <a name="Indexing"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Scope-of-variables">Scope of variables</a>, Previous: <a rel="previous" accesskey="p" href="#Elementary-arithmetic-operations">Elementary arithmetic operations</a>, Up: <a rel="up" accesskey="u" href="#Evaluation-of-expressions">Evaluation of expressions</a> </div> <h3 class="section">3.4 Indexing</h3> <p>R contains several constructs which allow access to individual elements or subsets through indexing operations. In the case of the basic vector types one can access the i-th element using <code>x[i]</code>, but there is also indexing of lists, matrices, and multi-dimensional arrays. There are several forms of indexing in addition to indexing with a single integer. Indexing can be used both to extract part of an object and to replace parts of an object (or to add parts). <p>R has three basic indexing operators, with syntax displayed by the following examples <pre class="example"> x[i] x[i, j] x[[i]] x[[i, j]] x$a x$"a" </pre> <p><a name="index-g_t_005b-112"></a><a name="index-g_t_005b_005b-113"></a><a name="index-g_t_0024-114"></a><a name="index-index-115"></a> For vectors and matrices the <code>[[</code> forms are rarely used, although they have some slight semantic differences from the <code>[</code> form (e.g. it drops any <code>names</code> or <code>dimnames</code> attribute, and that partial matching is used for character indices). When indexing multi-dimensional structures with a single index, <code>x[[i]]</code> or <code>x[i]</code> will return the <code>i</code>th sequential element of <code>x</code>. <p>For lists, one generally uses <code>[[</code> to select any single element, whereas <code>[</code> returns a list of the selected elements. <p>The <code>[[</code> form allows only a single element to be selected using integer or character indices, whereas <code>[</code> allows indexing by vectors. Note though that for a list or other recursive object, the index can be a vector and each element of the vector is applied in turn to the list, the selected component, the selected component of that component, and so on. The result is still a single element. <p>The form using <code>$</code> applies to recursive objects such as lists and pairlists. It allows only a literal character string or a symbol as the index. That is, the index is not computable: for cases where you need to evaluate an expression to find the index, use <code>x[[expr]]</code>. When <code>$</code> is applied to a non-recursive object the result used to be always <code>NULL</code>: as from R 2.6.0 this is an error. <ul class="menu"> <li><a accesskey="1" href="#Indexing-by-vectors">Indexing by vectors</a> <li><a accesskey="2" href="#Indexing-matrices-and-arrays">Indexing matrices and arrays</a> <li><a accesskey="3" href="#Indexing-other-structures">Indexing other structures</a> <li><a accesskey="4" href="#Subset-assignment">Subset assignment</a> </ul> <div class="node"> <a name="Indexing-by-vectors"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Indexing-matrices-and-arrays">Indexing matrices and arrays</a>, Previous: <a rel="previous" accesskey="p" href="#Indexing">Indexing</a>, Up: <a rel="up" accesskey="u" href="#Indexing">Indexing</a> </div> <h4 class="subsection">3.4.1 Indexing by vectors</h4> <p>R allows some powerful constructions using vectors as indices. We shall discuss indexing of simple vectors first. For simplicity, assume that the expression is <code>x[i]</code>. Then the following possibilities exist according to the type of <code>i</code>. <ul> <li><a name="index-index-116"></a><strong>Integer</strong>. All elements of <code>i</code> must have the same sign. If they are positive, the elements of <code>x</code> with those index numbers are selected. If <code>i</code> contains negative elements, all elements except those indicated are selected. <p>If <code>i</code> is positive and exceeds <code>length(x)</code> then the corresponding selection is <code>NA</code>. A negative out of bounds value for <code>i</code> causes an error. <p>A special case is the zero index, which has null effects: <code>x[0]</code> is an empty vector and otherwise including zeros among positive or negative indices has the same effect as if they were omitted. <!-- Are there any useful uses of zero indices?? --> <li><strong>Other numeric</strong>. Non-integer values are converted to integer (by truncation towards zero) before use. <li><strong>Logical</strong>. The indexing <code>i</code> should generally have the same length as <code>x</code>. If it is shorter, then its elements will be recycled as discussed in <a href="#Elementary-arithmetic-operations">Elementary arithmetic operations</a>. If it is longer, then <code>x</code> is conceptually extended with <code>NA</code>s. The selected values of <code>x</code> are those for which <code>i</code> is <code>TRUE</code>. <!-- @findex TRUE --> <!-- @findex FALSE --> <p><a name="index-partial-matching-117"></a><li><strong>Character</strong>. The strings in <code>i</code> are matched against the names attribute of <code>x</code> and the resulting integers are used. For <code>[[</code> and <code>$</code> partial matching is used if exact matching fails, so <code>x$aa</code> will match <code>x$aabb</code> if <code>x</code> does not contain a component named <code>"aa"</code> and <code>"aabb"</code> is the only name which has prefix <code>"aa"</code>. For <code>[[</code>, partial matching can be controlled via the <code>exact</code> argument which defaults to <code>NA</code> indicating that partial matching is allowed, but should result in a warning when it occurs. Setting <code>exact</code> to <code>TRUE</code> prevents partial matching from occurring, a <code>FALSE</code> value allows it and does not issue any warnings. Note that <code>[</code> always requires an exact match. The string <code>""</code> is treated specially: it indicates ‘no name’ and matches no element (not even those without a name). Note that partial matching is only used when extracting and not when replacing. <li><strong>Factor</strong>. The result is identical to <code>x[as.integer(i)]</code>. The factor levels are never used. If so desired, use <code>x[as.character(i)]</code> or a similar construction. <li><strong>Empty</strong>. The expression <code>x[]</code> returns <code>x</code>, but drops “irrelevant” attributes from the result. Only <code>names</code> and in multi-dimensional arrays <code>dim</code> and <code>dimnames</code> attributes are retained. <li><strong>NULL</strong>. This is treated as if it were <code>integer(0)</code>. </ul> <p>Indexing with a missing (i.e. <code>NA</code>) value gives an <code>NA</code> result. This rule applies also to the case of logical indexing, i.e. the elements of <code>x</code> that have an <code>NA</code> selector in <code>i</code> get included in the result, but their value will be <code>NA</code>. <a name="index-NA-118"></a> Notice however, that there are different modes of <code>NA</code>—the literal constant is of mode <code>"logical"</code>, but it is frequently automatically coerced to other types. One effect of this is that <code>x[NA]</code> has the length of <code>x</code>, but <code>x[c(1, NA)]</code> has length 2. That is because the rules for logical indices apply in the former case, but those for integer indices in the latter. <p>Indexing with <code>[</code> will also carry out the relevant subsetting of any names attributes. <div class="node"> <a name="Indexing-matrices-and-arrays"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Indexing-other-structures">Indexing other structures</a>, Previous: <a rel="previous" accesskey="p" href="#Indexing-by-vectors">Indexing by vectors</a>, Up: <a rel="up" accesskey="u" href="#Indexing">Indexing</a> </div> <h4 class="subsection">3.4.2 Indexing matrices and arrays</h4> <p><a name="index-index-119"></a>Subsetting multi-dimensional structures generally follows the same rules as single-dimensional indexing for each index variable, with the relevant component of <code>dimnames</code> taking the place of <code>names</code>. A couple of special rules apply, though: <p>Normally, a structure is accessed using the number of indices corresponding to its dimension. It is however also possible to use a single index in which case the <code>dim</code> and <code>dimnames</code> attributes are disregarded and the result is effectively that of <code>c(m)[i]</code>. Notice that <code>m[1]</code> is usually very different from <code>m[1, ]</code> or <code>m[, 1]</code>. <p>It is possible to use a matrix of integers as an index. In this case, the number of columns of the matrix should match the number of dimensions of the structure, and the result will be a vector with length as the number of rows of the matrix. The following example shows how to extract the elements <code>m[1, 1]</code> and <code>m[2, 2]</code> in one operation. <pre class="example"> > m <- matrix(1:4, 2) > m [,1] [,2] [1,] 1 3 [2,] 2 4 > i <- matrix(c(1, 1, 2, 2), 2, byrow = TRUE) > i [,1] [,2] [1,] 1 1 [2,] 2 2 > m[i] [1] 1 4 </pre> <p class="noindent">Negative indices are not allowed in indexing matrices. <code>NA</code> and zero values are allowed: rows in an index matrix containing a zero are ignored, whereas rows containing an <code>NA</code> produce an <code>NA</code> in the result. <p>Both in the case of using a single <a name="index-index-120"></a>index and in matrix indexing, a <code>names</code> attribute is used if present, as had the structure been one-dimensional. <p>If an indexing operation causes the result to have one of its extents of length one, as in selecting a single slice of a three-dimensional matrix with (say) <code>m[2, , ]</code>, the corresponding dimension is generally dropped from the result. If a single-dimensional structure results, a vector is obtained. This is occasionally undesirable and can be turned off by adding the ‘<samp><span class="samp">drop = FALSE</span></samp>’ to the indexing operation. Notice that this is an additional argument to the <code>[</code> function and doesn't add to the index count. Hence the correct way of selecting the first row of a matrix as a 1 by n matrix is <code>m[1, , drop = FALSE]</code>. Forgetting to disable the dropping feature is a common cause of failure in general subroutines where an index occasionally, but not usually has length one. This rule still applies to a one-dimensional array, where any subsetting will give a vector result unless ‘<samp><span class="samp">drop = FALSE</span></samp>’ is used. <p>Notice that vectors are distinct from one-dimensional arrays in that the latter have <code>dim</code> and <code>dimnames</code> attributes (both of length one). One-dimensional arrays are not easily obtained from subsetting operations but they can be constructed explicitly and are returned by <code>table</code>. This is sometimes useful because the elements of the <code>dimnames</code> list may themselves be named, which is not the case for the <code>names</code> attribute. <p>Some operations such as <code>m[FALSE, ]</code> result in structures in which a dimension has zero extent. R generally tries to handle these structures sensibly. <div class="node"> <a name="Indexing-other-structures"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Subset-assignment">Subset assignment</a>, Previous: <a rel="previous" accesskey="p" href="#Indexing-matrices-and-arrays">Indexing matrices and arrays</a>, Up: <a rel="up" accesskey="u" href="#Indexing">Indexing</a> </div> <h4 class="subsection">3.4.3 Indexing other structures</h4> <p>The operator <code>[</code> is a generic function which allows class methods to be added, and the <code>$</code> and <code>[[</code> operators likewise. Thus, it is possible to have user-defined indexing operations for any structure. Such a function, say <code>[.foo</code> is called with a set of arguments of which the first is the structure being indexed and the rest are the indices. In the case of <code>$</code>, the index argument is of mode <code>"symbol"</code> even when using the <code>x$"abc"</code> form. It is important to be aware that class methods do not necessarily behave in the same way as the basic methods, for example with respect to partial matching. <p>The most important example of a class method for <code>[</code> is that used for data frames. It is not be described in detail here (see the help page for <code>[.data.frame</code>, but in broad terms, if two indices are supplied (even if one is empty) it creates matrix-like indexing for a structure that is basically a list of vectors of the same length. If a single index is supplied, it is interpreted as indexing the list of columns—in that case the <code>drop</code> argument is ignored, with a warning. <p>The basic operators <code>$</code> and <code>[[</code> can be applied to environments. Only character indices are allowed and no partial matching is done. <div class="node"> <a name="Subset-assignment"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Indexing-other-structures">Indexing other structures</a>, Up: <a rel="up" accesskey="u" href="#Indexing">Indexing</a> </div> <h4 class="subsection">3.4.4 Subset assignment</h4> <p><a name="index-assignment-121"></a><a name="index-complex-assignment-122"></a> Assignment to subsets of a structure is a special case of a general mechanism for complex assignment: <pre class="example"> x[3:5] <- 13:15 </pre> <p>The result of this commands is as if the following had been executed <pre class="example"> `*tmp*` <- x x <- "[<-"(`*tmp*`, 3:5, value=13:15) rm(`*tmp*`) </pre> <p>Note that the index is first converted to a numeric index and then the elements are replaced sequentially along the numeric index, as if a <code>for</code> loop had been used. Any existing variable called <code>`*tmp*`</code> will be overwritten and deleted, and this variable name should not be used in code. <p>The same mechanism can be applied to functions other than <code>[</code>. The replacement function has the same name with <code><-</code> pasted on. Its last argument, which must be called <code>value</code>, is the new value to be assigned. For example, <pre class="example"> names(x) <- c("a","b") </pre> <p>is equivalent to <pre class="example"> `*tmp*` <- x x <- "names<-"(`*tmp*`, value=c("a","b")) rm(`*tmp*`) </pre> <p>Nesting of complex assignments is evaluated recursively <pre class="example"> names(x)[3] <- "Three" </pre> <p>is equivalent to <pre class="example"> `*tmp*` <- x x <- "names<-"(`*tmp*`, value="[<-"(names(`*tmp*`), 3, value="Three")) rm(`*tmp*`) </pre> <p>Complex assignments in the enclosing environment (using <code><<-</code>) are also permitted: <pre class="example"> names(x)[3] <<- "Three" </pre> <p>is equivalent to <pre class="example"> `*tmp*` <<- get(x, envir=parent.env(), inherits=TRUE) names(`*tmp*`)[3] <- "Three" x <<- `*tmp*` rm(`*tmp*`) </pre> <p>and also to <pre class="example"> `*tmp*` <- get(x,envir=parent.env(), inherits=TRUE) x <<- "names<-"(`*tmp*`, value="[<-"(names(`*tmp*`), 3, value="Three")) rm(`*tmp*`) </pre> <p>Only the target variable is evaluated in the enclosing environment, so <pre class="example"> e<-c(a=1,b=2) i<-1 local({ e <- c(A=10,B=11) i <-2 e[i] <<- e[i]+1 }) </pre> <p>uses the local value of <code>i</code> on both the LHS and RHS, and the local value of <code>e</code> on the RHS of the superassignment statement. It sets <code>e</code> in the outer environment to <pre class="example"> a b 1 12 </pre> <p>That is, the superassignment is equivalent to the four lines <pre class="example"> `*tmp*` <- get(x,envir=parent.env(), inherits=TRUE) `*tmp*`[i] <- e[i]+1 x <<- `*tmp*` rm(`*tmp*`) </pre> <p>Similarly <pre class="example"> x[is.na(x)] <<- 0 </pre> <p>is equivalent to <pre class="example"> `*tmp*` <- get(x,envir=parent.env(), inherits=TRUE) `*tmp*`[is.na(x)] <- 0 x <<- `*tmp*` rm(`*tmp*`) </pre> <p>and not to <pre class="example"> `*tmp*` <- get(x,envir=parent.env(), inherits=TRUE) `*tmp*`[is.na(`*tmp*`)] <- 0 x <<- `*tmp*` rm(`*tmp*`) </pre> <p>These two candidate interpretations differ only if there is also a local variable <code>x</code>. It is a good idea to avoid having a local variable with the same name as the target variable of a superassignment. As this case was handled incorrectly in versions 1.9.1 and earlier there must not be a serious need for such code. <!-- Example session sketch --> <!-- @example --> <!-- Make some data --> <!-- > x <- rbinom(10,5,.5) --> <!-- > x --> <!-- [1] 3 2 3 0 1 1 0 4 3 1 --> <!-- Select one element --> <!-- > x[6] --> <!-- [1] 1 --> <!-- Select several --> <!-- > x[6:10] --> <!-- [1] 1 0 4 3 1 --> <!-- Select by condition --> <!-- > x[x>=3] --> <!-- [1] 3 3 4 3 --> <!-- ..by name (add element names first) --> <!-- > names(x)<-letters[1:10] --> <!-- > x --> <!-- a b c d e f g h i j --> <!-- 3 2 3 0 1 1 0 4 3 1 --> <!-- > x["e"] --> <!-- e --> <!-- 1 --> <!-- Notice that names vector is subsetted as well: --> <!-- > names(x[x>=3]) --> <!-- [1] "a" "c" "h" "i" --> <!-- Indexing with [[ drops names attrib. whereas [ keeps (and subsets) it. --> <!-- > x[[4]] --> <!-- [1] 0 --> <!-- > x[4] --> <!-- d --> <!-- 0 --> <!-- [[ also works on matrices --> <!-- > a<-matrix(1:4,2) --> <!-- > a[[2,2]] --> <!-- [1] 4 --> <!-- However, one can not use fancy indexes: --> <!-- > x[[1:4]] --> <!-- Error: attempt to select more than one element --> <!-- [need examples of basic matrix operations, empty indexes, drop=TRUE/FALSE] --> <!-- @end example --> <div class="node"> <a name="Scope-of-variables"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Indexing">Indexing</a>, Up: <a rel="up" accesskey="u" href="#Evaluation-of-expressions">Evaluation of expressions</a> </div> <h3 class="section">3.5 Scope of variables</h3> <p><a name="index-scope-123"></a> <a name="index-name-124"></a>Almost every programming language has a set of scoping rules, allowing the same name to be used for different objects. This allows, e.g., a local variable in a function to have the same name as a global object. <p>R uses a <em>lexical scoping</em> model, similar to languages like Pascal. However, R is a <em>functional programming language</em> and allows dynamic creation and manipulation of functions and language objects, and has additional features reflecting this fact. <ul class="menu"> <li><a accesskey="1" href="#Global-environment">Global environment</a> <li><a accesskey="2" href="#Lexical-environment">Lexical environment</a> <li><a accesskey="3" href="#Stacks">Stacks</a> <li><a accesskey="4" href="#Search-path">Search path</a> </ul> <div class="node"> <a name="Global-environment"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Lexical-environment">Lexical environment</a>, Previous: <a rel="previous" accesskey="p" href="#Scope-of-variables">Scope of variables</a>, Up: <a rel="up" accesskey="u" href="#Scope-of-variables">Scope of variables</a> </div> <h4 class="subsection">3.5.1 Global environment</h4> <p>The global <a name="index-environment-125"></a>environment is the root of the user workspace. An <a name="index-assignment-126"></a>assignment operation from the command line will cause the relevant object to belong to the global environment. Its enclosing environment is the next environment on the search path, and so on back to the empty environment that is the enclosure of the base environment. <div class="node"> <a name="Lexical-environment"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Stacks">Stacks</a>, Previous: <a rel="previous" accesskey="p" href="#Global-environment">Global environment</a>, Up: <a rel="up" accesskey="u" href="#Scope-of-variables">Scope of variables</a> </div> <h4 class="subsection">3.5.2 Lexical environment</h4> <p>Every call to a <a name="index-function-127"></a>function creates a <a name="index-frame-128"></a><a name="index-environment-129"></a><em>frame</em> which contains the local variables created in the function, and is evaluated in an environment, which in combination creates a new environment. <p>Notice the terminology: A frame is a set of variables, an environment is a nesting of frames (or equivalently: the innermost frame plus the enclosing environment). <p>Environments may be assigned to variables or be contained in other objects. However, notice that they are not standard objects—in particular, they are not copied on assignment. <p>A closure (mode <code>"function"</code>) object will contain the environment in which it is created as part of its definition (By default. The environment can be manipulated using <code>environment<-</code>). When the function is subsequently called, its <a name="index-environment_002c-evaluation-130"></a>evaluation environment is created with the closure's environment as enclosure. Notice that this is not necessarily the environment of the caller! <p>Thus, when a variable is requested inside a <a name="index-function-131"></a>function, it is first sought in the <a name="index-environment_002c-evaluation-132"></a>evaluation environment, then in the enclosure, the enclosure of the enclosure, etc.; once the global environment or the environment of a package is reached, the search continues up the search path to the environment of the base package. If the variable is not found there, the search will proceed next to the empty environment, and will fail. <div class="node"> <a name="Stacks"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Search-path">Search path</a>, Previous: <a rel="previous" accesskey="p" href="#Lexical-environment">Lexical environment</a>, Up: <a rel="up" accesskey="u" href="#Scope-of-variables">Scope of variables</a> </div> <h4 class="subsection">3.5.3 The call stack</h4> <p>Every time a <a name="index-function-133"></a>function is invoked a new evaluation frame is created. At any point in time during the computation the currently active environments are accessible through the <em>call stack</em>. Each time a function is invoked a special construct called a context is created internally and is placed on a list of contexts. When a function has finished evaluating its context is removed from the call stack. <p>Making variables defined higher up the call stack available is called <a name="index-scope-134"></a>dynamic scope. The binding for a variable is then determined by the most recent (in time) definition of the variable. This contradicts the default scoping rules in R, which use the bindings in the <a name="index-environment-135"></a>environment in which the function was defined (lexical scope). Some functions, particularly those that use and manipulate model formulas, need to simulate dynamic scope by directly accessing the call stack. <p>Access to the <a name="index-call-stack-136"></a>call stack is provided through a family of functions which have names that start with ‘<samp><span class="samp">sys.</span></samp>’. They are listed briefly below. <p><a name="index-evaluation-137"></a> <dl> <dt><code>sys.call</code><dd>Get the call for the specified context. <br><dt><code>sys.frame</code><dd>Get the evaluation frame for the specified context. <br><dt><code>sys.nframe</code><dd>Get the environment frame for all active contexts. <br><dt><code>sys.function</code><dd>Get the function being invoked in the specified context. <br><dt><code>sys.parent</code><dd>Get the parent of the current function invocation. <br><dt><code>sys.calls</code><dd>Get the calls for all the active contexts. <br><dt><code>sys.frames</code><dd>Get the evaluation frames for all the active contexts. <br><dt><code>sys.parents</code><dd>Get the numeric labels for all active contexts. <br><dt><code>sys.on.exit</code><dd>Set a function to be executed when the specified context is exited. <br><dt><code>sys.status</code><dd>Calls <code>sys.frames</code>, <code>sys.parents</code> and <code>sys.calls</code>. <br><dt><code>parent.frame</code><dd>Get the evaluation frame for the specified parent context. </dl> <div class="node"> <a name="Search-path"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Stacks">Stacks</a>, Up: <a rel="up" accesskey="u" href="#Scope-of-variables">Scope of variables</a> </div> <h4 class="subsection">3.5.4 Search path</h4> <p>In addition to the evaluation <a name="index-environment-138"></a><a name="index-search-path-139"></a>environment structure, R has a search path of environments which are searched for variables not found elsewhere. This is used for two things: packages of functions and attached user data. <p>The first element of the search path is the global environment and the last is the base package. An <code>Autoloads</code> environment is used for holding proxy objects that may be loaded on demand. Other environments are inserted in the path using <code>attach</code> or <code>library</code>. <p><a name="index-namespace-140"></a>Packages which have a <em>namespace</em> have a different search path. When a search for an R object is started from an object in such a package, the package itself is searched first, then its imports, then the base namespace and finally the global environment and the rest of the regular search path. The effect is that references to other objects in the same package will be resolved to the package, and objects cannot be masked by objects of the same name in the global environment or in other packages. <div class="node"> <a name="Functions"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Object_002doriented-programming">Object-oriented programming</a>, Previous: <a rel="previous" accesskey="p" href="#Evaluation-of-expressions">Evaluation of expressions</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">4 Functions</h2> <ul class="menu"> <li><a accesskey="1" href="#Writing-functions">Writing functions</a> <li><a accesskey="2" href="#Functions-as-objects">Functions as objects</a> <li><a accesskey="3" href="#Evaluation">Evaluation</a> </ul> <div class="node"> <a name="Writing-functions"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Functions-as-objects">Functions as objects</a>, Previous: <a rel="previous" accesskey="p" href="#Functions">Functions</a>, Up: <a rel="up" accesskey="u" href="#Functions">Functions</a> </div> <h3 class="section">4.1 Writing functions</h3> <p>While R can be very useful as a data analysis tool most users very quickly find themselves wanting to write their own <a name="index-function-141"></a>functions. This is one of the real advantages of R. Users can program it and they can, if they want to, change the system level functions to functions that they find more appropriate. <p>R also provides facilities that make it easy to document any functions that you have created. See <a href="R-exts.html#Writing-R-documentation">Writing R documentation</a>. <ul class="menu"> <li><a accesskey="1" href="#Syntax-and-examples">Syntax and examples</a> <li><a accesskey="2" href="#Arguments">Arguments</a> </ul> <div class="node"> <a name="Syntax-and-examples"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Arguments">Arguments</a>, Previous: <a rel="previous" accesskey="p" href="#Writing-functions">Writing functions</a>, Up: <a rel="up" accesskey="u" href="#Writing-functions">Writing functions</a> </div> <h4 class="subsection">4.1.1 Syntax and examples</h4> <p>The syntax for writing a <a name="index-function-142"></a>function is <pre class="example"> function ( <var>arglist</var> ) <var>body</var> </pre> <p>The first component of the function declaration is the keyword <code>function</code> which indicates to R that you want to create a function. <p>An <a name="index-argument-143"></a>argument list is a comma separated list of formal arguments. A formal argument can be a symbol, a statement of the form ‘<samp><var>symbol</var><span class="samp"> = </span><var>expression</var></samp>’, or the special formal argument ‘<samp><span class="samp">...</span></samp>’. <p>The <em>body</em> can be any valid R expression. Generally, the body is a group of expressions contained in curly braces (‘<samp><span class="samp">{</span></samp>’ and ‘<samp><span class="samp">}</span></samp>’). <p>Generally <a name="index-function-144"></a>functions are assigned to symbols but they don't need to be. The value returned by the call to <code>function</code> is a function. If this is not given a name it is referred to as an <a name="index-function_002c-anonymous-145"></a>anonymous function. Anonymous functions are most frequently used as arguments other functions such as the <code>apply</code> family or <code>outer</code>. <p>Here is a simple function: <code>echo <- function(x) print(x)</code>. So <code>echo</code> is a function that takes a single argument and when <code>echo</code> is invoked it prints its argument. <div class="node"> <a name="Arguments"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Syntax-and-examples">Syntax and examples</a>, Up: <a rel="up" accesskey="u" href="#Writing-functions">Writing functions</a> </div> <h4 class="subsection">4.1.2 Arguments</h4> <p>The formal arguments to the function define the variables whose values will be supplied at the time the function is invoked. The names of these arguments can be used within the function body where they obtain the value supplied at the time of function invocation. <p><a name="index-argument_002c-default-values-146"></a>Default values for arguments can be specified using the special form ‘<samp><var>name</var><span class="samp"> = </span><var>expression</var></samp>’. In this case, if the user does not specify a value for the argument when the function is invoked the expression will be associated with the corresponding symbol. When a value is needed the <var>expression</var> is <a name="index-evaluation_002c-expression-147"></a>evaluated in the evaluation frame of the function. <p>Default behaviours can also be specified by using the function <code>missing</code>. When <code>missing</code> is called with the <a name="index-name-148"></a>name of a formal argument it returns <code>TRUE</code> if the formal argument was not matched with any actual argument and has not been subsequently modified in the body of the function. An argument that is <code>missing</code> will thus have its default value, if any. The <code>missing</code> function does not force evaluation of the argument. <p>The special type of argument ‘<samp><span class="samp">...</span></samp>’ can contain any number of supplied arguments. It is used for a variety of purposes. It allows you to write a <a name="index-function-149"></a>function that takes an arbitrary number of arguments. It can be used to absorb some arguments into an intermediate function which can then be extracted by functions called subsequently. <div class="node"> <a name="Functions-as-objects"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Evaluation">Evaluation</a>, Previous: <a rel="previous" accesskey="p" href="#Writing-functions">Writing functions</a>, Up: <a rel="up" accesskey="u" href="#Functions">Functions</a> </div> <h3 class="section">4.2 Functions as objects</h3> <p>Functions are first class objects in R. They can be used anywhere that an R object is required. In particular they can be passed as arguments to functions and returned as values from functions. See <a href="#Function-objects">Function objects</a> for the details. <div class="node"> <a name="Evaluation"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Functions-as-objects">Functions as objects</a>, Up: <a rel="up" accesskey="u" href="#Functions">Functions</a> </div> <h3 class="section">4.3 Evaluation</h3> <ul class="menu"> <li><a accesskey="1" href="#Evaluation-environment">Evaluation environment</a> <li><a accesskey="2" href="#Argument-matching">Argument matching</a> <li><a accesskey="3" href="#Argument-evaluation">Argument evaluation</a> <li><a accesskey="4" href="#Scope">Scope</a> </ul> <div class="node"> <a name="Evaluation-environment"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Argument-matching">Argument matching</a>, Previous: <a rel="previous" accesskey="p" href="#Evaluation">Evaluation</a>, Up: <a rel="up" accesskey="u" href="#Evaluation">Evaluation</a> </div> <h4 class="subsection">4.3.1 Evaluation environment</h4> <p>When a <a name="index-function-150"></a>function is called or invoked a new <a name="index-evaluation-151"></a>evaluation frame is created. In this frame the formal arguments are matched with the supplied arguments according to the rules given in <a href="#Argument-matching">Argument matching</a>. The statements in the body of the function are evaluated sequentially in this <a name="index-environment-152"></a>environment frame. <p>The enclosing frame of the evaluation frame is the environment frame associated with the function being invoked. This may be different from S. While many functions have <code>.GlobalEnv</code> as their environment this does not have to be true and functions defined in packages with namespaces (normally) have the package namespace as their environment. <div class="node"> <a name="Argument-matching"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Argument-evaluation">Argument evaluation</a>, Previous: <a rel="previous" accesskey="p" href="#Evaluation-environment">Evaluation environment</a>, Up: <a rel="up" accesskey="u" href="#Evaluation">Evaluation</a> </div> <h4 class="subsection">4.3.2 Argument matching</h4> <p>This subsection applies to closures but not to primitive functions. The latter typically ignore tags and do positional matching, but their help pages should be consulted for exceptions, which include <code>log</code>, <code>round</code>, <code>signif</code>, <code>rep</code> and <code>seq.int</code>. <p>The first thing that occurs in a <a name="index-function-153"></a>function evaluation is the matching of formal to the actual or supplied arguments. This is done by a three-pass process: <ol type=1 start=1> <li><strong>Exact matching on tags</strong>. <a name="index-name-154"></a>For each named supplied argument the list of formal arguments is searched for an item whose name matches exactly. It is an error to have the same formal argument match several actuals or vice versa. <li><strong>Partial matching on tags</strong>. Each remaining named supplied argument is compared to the remaining formal arguments using partial matching. If the name of the supplied argument matches exactly with the first part of a formal argument then the two arguments are considered to be matched. It is an error to have multiple partial matches. Notice that if <code>f <- function(fumble, fooey) fbody</code>, then <code>f(f = 1, fo = 2)</code> is illegal, even though the 2nd actual argument only matches <code>fooey</code>. <code>f(f = 1, fooey = 2)</code> <em>is</em> legal though since the second argument matches exactly and is removed from consideration for partial matching. If the formal arguments contain ‘<samp><span class="samp">...</span></samp>’ then partial matching is only applied to arguments that precede it. <li><strong>Positional matching</strong>. Any unmatched formal arguments are bound to <em>unnamed</em> supplied arguments, in order. If there is a ‘<samp><span class="samp">...</span></samp>’ argument, it will take up the remaining arguments, tagged or not. </ol> <p>If any arguments remain unmatched an error is declared. <p>Argument matching is augmented by the functions <code>match.arg</code>, <code>match.call</code> and <code>match.fun</code>. <a name="index-match_002earg-155"></a><a name="index-match_002ecall-156"></a><a name="index-match_002efun-157"></a>Access to the partial matching algorithm used by R is via <code>pmatch</code>. <div class="node"> <a name="Argument-evaluation"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Scope">Scope</a>, Previous: <a rel="previous" accesskey="p" href="#Argument-matching">Argument matching</a>, Up: <a rel="up" accesskey="u" href="#Evaluation">Evaluation</a> </div> <h4 class="subsection">4.3.3 Argument evaluation</h4> <p>One of the most important things to know about the <a name="index-evaluation_002c-argument-158"></a>evaluation of arguments to a <a name="index-function-159"></a>function is that supplied arguments and default arguments are treated differently. The supplied arguments to a function are evaluated in the evaluation frame of the calling function. The default arguments to a function are evaluated in the evaluation frame of the function. <p>The semantics of invoking a function in R argument are <em>call-by-value</em>. In general, supplied arguments behave as if they are local variables initialized with the value supplied and the <a name="index-name-160"></a>name of the corresponding formal argument. Changing the value of a supplied argument within a function will not affect the value of the variable in the calling frame. <p>R has a form of lazy evaluation of function arguments. Arguments are not evaluated until needed. It is important to realize that in some cases the argument will never be evaluated. Thus, it is bad style to use arguments to functions to cause side-effects. While in <strong>C</strong> it is common to use the form, <code>foo(x = y)</code> to invoke <code>foo</code> with the value of <code>y</code> and simultaneously to assign the value of <code>y</code> to <code>x</code> this same style should not be used in R. There is no guarantee that the argument will ever be evaluated and hence the <a name="index-assignment-161"></a>assignment may not take place. <p>It is also worth noting that the effect of <code>foo(x <- y)</code> if the argument is evaluated is to change the value of <code>x</code> in the calling <a name="index-environment-162"></a>environment and not in the <a name="index-environment_002c-evaluation-163"></a>evaluation environment of <code>foo</code>. <p>It is possible to access the actual (not default) expressions used as arguments inside the function. The mechanism is implemented via promises. When a <a name="index-function-164"></a>function is being evaluated the actual expression used as an argument is stored in the promise together with a pointer to the environment the function was called from. When (if) the argument is evaluated the stored expression is evaluated in the environment that the function was called from. Since only a pointer to the environment is used any changes made to that environment will be in effect during this evaluation. The resulting value is then also stored in a separate spot in the promise. Subsequent evaluations retrieve this stored value (a second evaluation is not carried out). Access to the unevaluated expression is also available using <code>substitute</code>. <!-- Because @R{} is a very --> <!-- flexible program it is possible to encounter promises in the interpreted --> <!-- language, however, users are advised not to rely on them in their own --> <!-- programs. --> <p>When a <a name="index-function-165"></a>function is called, each formal argument is assigned a promise in the local environment of the call with the expression slot containing the actual argument (if it exists) and the environment slot containing the environment of the caller. If no actual argument for a formal argument is given in the call and there is a default expression, it is similarly assigned to the expression slot of the formal argument, but with the <a name="index-environment-166"></a>environment set to the local environment. <p>The process of filling the value slot of a promise by <a name="index-evaluation-167"></a>evaluating the contents of the expression slot in the promises environment is called <em>forcing</em> the promise. A promise will only be forced once, the value slot content being used directly later on. <p>A promise is forced when its value is needed. This usually happens inside internal <a name="index-function-168"></a><a name="index-function_002c-internal-169"></a>functions, but a promise can also be forced by direct evaluation of the promise itself. This is occasionally useful when a default expression depends on the value of another formal argument or other variable in the local environment. This is seen in the following example where the lone <code>label</code> ensures that the label is based on the value of <code>x</code> before it is changed in the next line. <pre class="example"> function(x, label = deparse(x)) { label x <- x + 1 print(label) } </pre> <p>The expression slot of a promise can itself involve other promises. This happens whenever an unevaluated argument is passed as an argument to another function. When forcing a promise, other promises in its expression will also be forced recursively as they are evaluated. <div class="node"> <a name="Scope"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Argument-evaluation">Argument evaluation</a>, Up: <a rel="up" accesskey="u" href="#Evaluation">Evaluation</a> </div> <h4 class="subsection">4.3.4 Scope</h4> <p><a name="index-scope-170"></a>Scope or the scoping rules are simply the set of rules used by the <a name="index-evaluation_002c-symbol-171"></a>evaluator to find a value for a <a name="index-symbol-172"></a>symbol. Every computer language has a set of such rules. In R the rules are fairly simple but there do exist mechanisms for subverting the usual, or default rules. <p>R adheres to a set of rules that are called <em>lexical scope</em>. This means the variable <a name="index-binding-173"></a>bindings in effect at the time the expression was created are used to provide values for any unbound symbols in the expression. <p>Most of the interesting properties of <a name="index-scope-174"></a>scope are involved with evaluating <a name="index-function-175"></a>functions and we concentrate on this issue. A symbol can be either <a name="index-binding-176"></a>bound or unbound. All of the formal arguments to a function provide bound symbols in the body of the function. Any other symbols in the body of the function are either local variables or unbound variables. A local variable is one that is defined within the function. Because R has no formal definition of variables, they are simply used as needed, it can be difficult to determine whether a variable is local or not. Local variables must first be defined, this is typically done by having them on the left-hand side of an <a name="index-assignment-177"></a>assignment. <p>During the evaluation process if an unbound symbol is detected then R attempts to find a value for it. The scoping rules determine how this process proceeds. In R the <a name="index-environment-178"></a>environment of the function is searched first, then its enclosure and so on until the global environment is reached. <p>The global environment heads a search list of environments that are searched sequentially for a matching symbol. The value of the first match is then used. <p>When this set of rules is combined with the fact that <a name="index-function-179"></a>functions can be returned as values from other functions then some rather nice, but at first glance peculiar, properties obtain. <p>A simple example: <pre class="example"> f <- function() { y <- 10 g <- function(x) x + y return(g) } h <- f() h(3) </pre> <p><a name="index-evaluation-180"></a>A rather interesting question is what happens when <code>h</code> is evaluated. To describe this we need a bit more notation. Within a <a name="index-function-181"></a>function body variables can be bound, local or unbound. The bound variables are those that match the formal arguments to the function. The local variables are those that were created or defined within the function body. The unbound variables are those that are neither local nor bound. When a function body is evaluated there is no problem determining values for local variables or for bound variables. Scoping rules determine how the language will find values for the unbound variables. <p>When <code>h(3)</code> is evaluated we see that its body is that of <code>g</code>. Within that body <code>x</code> is bound to the formal argument and <code>y</code> is unbound. In a language with <a name="index-scope-182"></a>lexical scope <code>x</code> will be associated with the value 3 and <code>y</code> with the value 10 local to <code>f</code> so <code>h(3)</code> should return the value 13. In R this is indeed what happens. <p>In S, because of the different scoping rules one will get an error indicating that <code>y</code> is not found, unless there is a variable <code>y</code> in your workspace in which case its value will be used. <!-- This is not correct! --> <!-- The scoping rules in @Sl{} are to look in the current frame and then in --> <!-- the global --> <!-- @cindex environment --> <!-- environment or workspace. These rules are very similar to --> <!-- the scoping rules used in the @code{C} language. --> <!-- @node Closures, , Evaluation, Functions --> <!-- section Closures --> <!-- A @emph{closure} is a --> <!-- @cindex function --> <!-- function together with an environment that --> <!-- provides bindings for any free variables in the closure. Since many --> <!-- @R{} functions are bound to environments they are often referred to as --> <!-- closures. --> <!-- FIXME dot-dot-dot semantics definitely needs somewhere to go --> <!-- @node Miscellanea, , Closures, Functions --> <!-- @section Miscellanea --> <!-- g(...), ..1, --> <!-- Recall() --> <div class="node"> <a name="Object-oriented-programming"></a> <a name="Object_002doriented-programming"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Computing-on-the-language">Computing on the language</a>, Previous: <a rel="previous" accesskey="p" href="#Functions">Functions</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">5 Object-oriented programming</h2> <p><a name="index-object_002doriented-183"></a>Object-oriented programming is a style of programming that has become popular in recent years. Much of the popularity comes from the fact that it makes it easier to write and maintain complicated systems. It does this through several different mechanisms. <p>Central to any object-oriented language are the concepts of class and of methods. A <em>class</em> is a definition of an object. Typically a class contains several <em>slots</em> that are used to hold class-specific information. An object in the language must be an instance of some class. Programming is based on objects or instances of classes. <p>Computations are carried out via <em>methods</em>. Methods are basically <a name="index-function-184"></a>functions that are specialized to carry out specific calculations on objects, usually of a specific class. This is what makes the language object oriented. In R, <em>generic functions</em> are used to determine the appropriate method. The generic function is responsible for determining the class of its argument(s) and uses that information to select the appropriate method. <p>Another feature of most object-oriented languages is the concept of inheritance. In most programming problems there are usually many objects that are related to one another. The programming is considerably simplified if some components can be reused. <p>If a class inherits from another class then generally it gets all the slots in the parent class and can extend it by adding new slots. On method dispatching (via the generic functions) if a method for the class does not exist then a method for the parent is sought. <p>In this chapter we discuss how this general strategy has been implemented in R and discuss some of the limitations within the current design. One of the advantages that most object systems impart is greater consistency. This is achieved via the rules that are checked by the compiler or interpreter. Unfortunately because of the way that the object system is incorporated into R this advantage does not obtain. Users are cautioned to use the object system in a straightforward manner. While it is possible to perform some rather interesting feats these tend to lead to obfuscated code and may depend on implementation details that will not be carried forward. <p>The greatest use of object oriented programming in R is through <code>print</code> methods, <code>summary</code> methods and <code>plot</code> methods. These methods allow us to have one generic <a name="index-function_002c-generic-185"></a>function call, <code>plot</code> say, that dispatches on the type of its argument and calls a plotting function that is specific to the data supplied. <p>In order to make the concepts clear we will consider the implementation of a small system designed to teach students about probability. In this system the objects are probability functions and the methods we will consider are methods for finding moments and for plotting. Probabilities can always be represented in terms of the cumulative distribution function but can often be represented in other ways. For example as a density, when it exists or as a moment generating function when it exists. <!-- FIXME --> <!-- This example needs help. MGFs are not used at all, and neither are --> <!-- the generic functions. Also, note that the terminology ‘pdf’ and --> <!-- ‘cdf’ may be confusing given the S use of ‘density’ and ‘probability’ --> <!-- functions. --> <!-- So we can begin by considering a system with three classes, --> <!-- @code{"cdf"}, @code{"pdf"} and @code{"mgf"} and three generic functions, --> <!-- @code{print}, @code{plot}, and @code{moment}. Each of the classes can --> <!-- be extended in numerous ways; for example we might want a parametric --> <!-- representation for some of the more common distributions. --> <!-- </FIXME> --> <ul class="menu"> <li><a accesskey="1" href="#Definition">Definition</a> <li><a accesskey="2" href="#Inheritance">Inheritance</a> <li><a accesskey="3" href="#Method-dispatching">Method dispatching</a> <li><a accesskey="4" href="#UseMethod">UseMethod</a> <li><a accesskey="5" href="#NextMethod">NextMethod</a> <li><a accesskey="6" href="#Group-methods">Group methods</a> <li><a accesskey="7" href="#Writing-methods">Writing methods</a> </ul> <div class="node"> <a name="Definition"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Inheritance">Inheritance</a>, Previous: <a rel="previous" accesskey="p" href="#Object_002doriented-programming">Object-oriented programming</a>, Up: <a rel="up" accesskey="u" href="#Object_002doriented-programming">Object-oriented programming</a> </div> <h3 class="section">5.1 Definition</h3> <p>Rather than having a full-fledged <a name="index-object_002doriented-186"></a>object-oriented system R has a class system and a mechanism for dispatching based on the class of an object. The dispatch mechanism for interpreted code relies on four special objects that are stored in the evaluation frame. These special objects are <code>.Generic</code>, <code>.Class</code>, <code>.Method</code> and <code>.Group</code>. There is a separate dispatch mechanism used for internal functions and types that will be discussed elsewhere. <p>The class system is facilitated through the <code>class</code> attribute. This attribute is a list of class names. So to create an object of class <code>"foo"</code> one simply attaches a class attribute with the string ‘<samp><span class="samp">"foo"</span></samp>’ in it. Thus, virtually anything can be turned in to an object of class <code>"foo"</code>. <p>The object system makes use of <a name="index-function_002c-generic-187"></a><em>generic functions</em> via two dispatching functions, <code>UseMethod</code> and <code>NextMethod</code>. The typical use of the object system is to begin by calling a generic function. This is typically a very simple function and consists of a single line of code. The system function <code>mean</code> is just such a function, <pre class="example"> > mean function (x, ...) UseMethod("mean") </pre> <p>When <code>mean</code> is called it can have any number of arguments but its first argument is special and the class of that first argument is used to determine which method should be called. The variable <code>.Class</code> is set to the class attribute of <code>x</code>, <code>.Generic</code> is set to the string <code>"mean"</code> and a search is made for the correct method to invoke. The class attributes of any other arguments to <code>mean</code> are ignored. <p>Suppose that <code>x</code> had a class attribute that contained <code>"foo"</code> and <code>"bar"</code>, in that order. Then R would first search for a function called <code>mean.foo</code> and if it did not find one it would then search for a function <code>mean.bar</code> and if that search was also unsuccessful then a final search for <code>mean.default</code> would be made. If the last search is unsuccessful R reports an error. It is a good idea to always write a default method. Note that the functions <code>mean.foo</code> etc. are referred to, in this context, as methods. <p><code>NextMethod</code> provides another mechanism for dispatching. A <a name="index-function-188"></a>function may have a call to <code>NextMethod</code> anywhere in it. The determination of which method should then be invoked is based primarily on the current values of <code>.Class</code> and <code>.Generic</code>. This is somewhat problematic since the method is really an ordinary function and users may call it directly. If they do so then there will be no values for <code>.Generic</code> or <code>.Class</code>. <p>If a method is invoked directly and it contains a call to <code>NextMethod</code> then the first argument to <code>NextMethod</code> is used to determine the <a name="index-function_002c-generic-189"></a>generic function. An error is signalled if this argument has not been supplied; it is therefore a good idea to always supply this argument. <p>In the case that a method is invoked directly the class attribute of the first argument to the method is used as the value of <code>.Class</code>. <p>Methods themselves employ <code>NextMethod</code> to provide a form of inheritance. Commonly a specific method performs a few operations to set up the data and then it calls the next appropriate method through a call to <code>NextMethod</code>. <!-- FIXME --> <!-- See also further above. --> <!-- We say that CDFs have three slots (perhaps should not used that --> <!-- terminology), but in the example we simply add a class attribute to a --> <!-- function, so where are the range and parameters? --> <!-- Now let's consider the distribution function example. We will assume --> <!-- that all objects of class @code{"cdf"} have three slots. They will have --> <!-- a @emph{range} slot that specifies the range or support of the --> <!-- distribution, a @emph{parameters} slot that contains a tagged list of --> <!-- the parameters and finally a @emph{fun} slot that contains the actual --> <!-- cdf. The @code{"pdf"} class will have the same three slots, however the --> <!-- function will be different. --> <!-- Suppose that we have the unit Exponential distribution. The following --> <!-- code segment defines objects of class @code{"cdf"} and @code{"pdf"} that --> <!-- represent the cdf and pdf or the unit Exponential. --> <!-- @example --> <!-- > ucexp <- function(x) 1 - exp(-x) --> <!-- > class(ucexp) <- "cdf" --> <!-- > udexp <- function(x) exp(-x) --> <!-- > class(udexp) <- "pdf" --> <!-- @end example --> <!-- @noindent --> <!-- Note that the corresponding classes have no slots and that there was --> <!-- nothing, apart from common sense, that prevented us from making --> <!-- @code{udexp} have class @code{"cdf"}. --> <!-- </FIXME> --> <p>Consider the following simple example. A point in two-dimensional Euclidean space can be specified by its Cartesian (x-y) or polar (r-theta) coordinates. Hence, to store information about the location of the point, we could define two classes, <code>"xypoint"</code> and <code>"rthetapoint"</code>. All the ‘xypoint’ data structures are lists with an x-component and a y-component. All ‘rthetapoint’ objects are lists with an r-component and a theta-component. <p>Now, suppose we want to get the x-position from either type of object. This can easily be achieved through <a name="index-function_002c-generic-190"></a>generic functions. We define the generic function <code>xpos</code> as follows. <pre class="example"> xpos <- function(x, ...) UseMethod("xpos") </pre> <p class="noindent">Now we can define methods: <pre class="example"> xpos.xypoint <- function(x) x$x xpos.rthetapoint <- function(x) x$r * cos(x$theta) </pre> <p>The user simply calls the function <code>xpos</code> with either representation as the argument. The internal dispatching method finds the class of the object and calls the appropriate methods. <p>It is pretty easy to add other representations. One need not write a new generic function only the methods. This makes it easy to add to existing systems since the user is only responsible for dealing with the new representation and not with any of the existing representations. <p>The bulk of the uses of this methodology are to provided specialized printing for objects of different types; there are about 40 methods for <code>print</code>. <div class="node"> <a name="Inheritance"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Method-dispatching">Method dispatching</a>, Previous: <a rel="previous" accesskey="p" href="#Definition">Definition</a>, Up: <a rel="up" accesskey="u" href="#Object_002doriented-programming">Object-oriented programming</a> </div> <h3 class="section">5.2 Inheritance</h3> <p><a name="index-evaluation-191"></a>The class attribute of an object can have several elements. When a <a name="index-function_002c-generic-192"></a>generic function is called the first inheritance is mainly handled through <code>NextMethod</code>. <code>NextMethod</code> determines the method currently being evaluated, finds the next class from th <p>FIXME: something is missing here <div class="node"> <a name="Method-dispatching"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#UseMethod">UseMethod</a>, Previous: <a rel="previous" accesskey="p" href="#Inheritance">Inheritance</a>, Up: <a rel="up" accesskey="u" href="#Object_002doriented-programming">Object-oriented programming</a> </div> <h3 class="section">5.3 Method dispatching</h3> <p><a name="index-function_002c-generic-193"></a>Generic functions should consist of a single statement. They should usually be of the form <code>foo <- function(x, ...) UseMethod("foo", x)</code>. When <code>UseMethod</code> is called, it determines the appropriate method and then that method is invoked with the same arguments, in the same order as the call to the generic, as if the call had been made directly to the method. <p>In order to determine the correct method the class attribute of the first argument to the generic is obtained and used to find the correct method. The <a name="index-name-194"></a>name of the generic function is combined with the first element of the class attribute into the form, <var>generic</var><code>.</code><var>class</var> and a function with that name is sought. If the function is found then it is used. If no such function is found then the second element of the class attribute is used, and so on until all the elements of the class attribute have been exhausted. If no method has been found at that point then the method <var>generic</var><code>.</code><var>default</var> is used. If the first argument to the generic function has no class attribute then <var>generic</var><code>.</code><var>default</var> is used. Since the introduction of namespaces the methods may not be accessible by their names (i.e. <code>get("</code><var>generic</var><code>.</code><var>class</var><code>")</code> may fail), but they will be accessible by <code>getS3method("</code><var>generic</var><code>","</code><var>class</var><code>")</code>. <p><a name="index-object-195"></a>Any object can have a <code>class</code> attribute. This attribute can have any number of elements. Each of these is a string that defines a class. When a generic function is invoked the class of its first argument is examined. <div class="node"> <a name="UseMethod"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#NextMethod">NextMethod</a>, Previous: <a rel="previous" accesskey="p" href="#Method-dispatching">Method dispatching</a>, Up: <a rel="up" accesskey="u" href="#Object_002doriented-programming">Object-oriented programming</a> </div> <h3 class="section">5.4 UseMethod</h3> <p><a name="index-UseMethod-196"></a> <code>UseMethod</code> is a special function and it behaves differently from other function calls. The syntax of a call to it is <code>UseMethod(</code><var>generic</var><code>, </code><var>object</var><code>)</code>, where <var>generic</var> is the name of the generic function, <var>object</var> is the object used to determine which method should be chosen. <code>UseMethod</code> can only be called from the body of a function. <p><a name="index-evaluation-197"></a><code>UseMethod</code> changes the evaluation model in two ways. First, when it is invoked it determines the next method (function) to be called. It then invokes that function using the current evaluation <a name="index-environment-198"></a>environment; this process will be described shortly. The second way in which <code>UseMethod</code> changes the evaluation environment is that it does not return control to the calling function. This means, that any statements after a call to <code>UseMethod</code> are guaranteed not to be executed. <p>When <code>UseMethod</code> is invoked the generic function is the specified value in the call to <code>UseMethod</code>. The object to dispatch on is either the supplied second argument or the first argument to the current function. The class of the argument is determined and the first element of it is combined with the name of the generic to determine the appropriate method. So, if the generic had name <code>foo</code> and the class of the object is <code>"bar"</code>, then R will search for a method named <code>foo.bar</code>. If no such method exists then the inheritance mechanism described above is used to locate an appropriate method. <p>Once a method has been determined R invokes it in a special way. Rather than creating a new evaluation <a name="index-environment-199"></a>environment R uses the environment of the current function call (the call to the generic). Any <a name="index-assignment-200"></a>assignments or evaluations that were made before the call to <code>UseMethod</code> will be in effect. The arguments that were used in the call to the generic are rematched to the formal arguments of the selected method. <p>When the method is invoked it is called with arguments that are the same in number and have the same names as in the call to the generic. They are matched to the arguments of the method according to the standard R rules for argument matching. However the object, i.e. the first argument has been evaluated. <p>The call to <code>UseMethod</code> has the effect of placing some special objects in the evaluation frame. They are <code>.Class</code>, <code>.Generic</code> and <code>.Method</code>. These special objects are used to by R to handle the method dispatch and inheritance. <code>.Class</code> is the class of the object, <code>.Generic</code> is the name of the generic function and <code>.Method</code> is the name of the method currently being invoked. If the method was invoked through one of the internal interfaces then there may also be an object called <code>.Group</code>. This will be described in Section <a href="#Group-methods">Group methods</a>. After the initial call to <code>UseMethod</code> these special variables, not the object itself, control the selection of subsequent methods. <p>The body of the method is then evaluated in the standard fashion. In particular variable look-up in the body follows the rules for the method. So if the method has an associated environment then that is used. In effect we have replaced the call to the generic by a call to the method. Any local <a name="index-assignment-201"></a>assignments in the frame of the generic will be carried forward into the call to the method. Use of this <em>feature</em> is discouraged. It is important to realize that control will never return to the generic and hence any expressions after a call to <code>UseMethod</code> will never be executed. <p>Any arguments to the generic that were evaluated prior to the call to <code>UseMethod</code> remain evaluated. <p>The arguments in the call to the generic are rematched with the arguments for the method using the standard argument matching mechanism. The first argument, i.e. the object, will have been evaluated. <p>If the first argument to <code>UseMethod</code> is not supplied it is assumed to be the name of the current function. If two arguments are supplied to <code>UseMethod</code> then the first is the name of the method and the second is assumed to be the object that will be dispatched on. It is evaluated so that the required method can be determined. In this case the first argument in the call to the generic is not evaluated and is discarded. There is no way to change the other arguments in the call to the method these remain as they were in the call to the generic. This is in contrast to <code>NextMethod</code> where the arguments in the call to the next method can be altered. <div class="node"> <a name="NextMethod"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Group-methods">Group methods</a>, Previous: <a rel="previous" accesskey="p" href="#UseMethod">UseMethod</a>, Up: <a rel="up" accesskey="u" href="#Object_002doriented-programming">Object-oriented programming</a> </div> <h3 class="section">5.5 NextMethod</h3> <p><a name="index-NextMethod-202"></a> <code>NextMethod</code> is used to provide a simple inheritance mechanism. <p>Methods invoked as a result of a call to <code>NextMethod</code> behave as if they had been invoked from the previous method. The arguments to the inherited method are in the same order and have the same names as the call to the current method. This means that they are the same as for the call to the generic. However, the expressions for the arguments are the names of the corresponding formal arguments of the current method. Thus the arguments will have values that correspond to their value at the time NextMethod was invoked. <p>Unevaluated arguments remain unevaluated. Missing arguments remain missing. <p>The syntax for a call to <code>NextMethod</code> is <code>NextMethod(generic, object, ...)</code>. If the <code>generic</code> is not supplied the value of <code>.Generic</code> is used. If the <code>object</code> is not supplied the first argument in the call to the current method is used. Values in the ‘<samp><span class="samp">...</span></samp>’ argument are used to modify the arguments of the next method. <p>It is important to realize that the choice of the next method depends on the current values of <code>.Generic</code> and <code>.Class</code> and not on the object. So changing the object in a call to <code>NextMethod</code> affects the arguments received by the next method but does not affect the choice of the next method. <p>Methods can be called directly. If they are then there will be no <code>.Generic</code>, <code>.Class</code> or <code>.Method</code>. In this case the <code>generic</code> argument of <code>NextMethod</code> must be specified. The value of <code>.Class</code> is taken to be the class attribute of the object which is the first argument to the current function. The value of <code>.Method</code> is the name of the current function. These choices for default values ensure that the behaviour of a method doesn't change depending on whether it is called directly or via a call to a generic. <!-- FIXME --> <p>An issue for discussion is the behaviour of the ‘<samp><span class="samp">...</span></samp>’ argument to <code>NextMethod</code>. The White Book describes the behaviour as follows: <p><a name="index-name-203"></a>- named arguments replace the corresponding arguments in the call to the current method. Unnamed arguments go at the start of the argument list. <p>What I would like to do is: <p>-first do the argument matching for NextMethod; -if the object or generic are changed fine -first if a named list element matches an argument (named or not) the list value replaces the argument value. - the first unnamed list element <p>Values for lookup: Class: comes first from .Class, second from the first argument to the method and last from the object specified in the call to NextMethod <p>Generic: comes first from .Generic, if nothing then from the first argument to the method and if it's still missing from the call to NextMethod <p>Method: this should just be the current function name. <!-- I don't know --> <!-- what its used for but I don't currently think it's involved in the --> <!-- dispatch. --> <!-- @node Implicit dispatching, Group methods, NextMethod, Object-oriented programming --> <!-- @section Implicit dispatching --> <!-- What is implicit dispatching???? --> <div class="node"> <a name="Group-methods"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Writing-methods">Writing methods</a>, Previous: <a rel="previous" accesskey="p" href="#NextMethod">NextMethod</a>, Up: <a rel="up" accesskey="u" href="#Object_002doriented-programming">Object-oriented programming</a> </div> <h3 class="section">5.6 Group methods</h3> <p>For several types of <a name="index-function_002c-internal-204"></a>internal functions R provides a dispatching mechanism for operators. This means that operators such as <code>==</code> or <code><</code> can have their behaviour modified for members of special classes. The functions and operators have been grouped into three categories and group methods can be written for each of these categories. There is currently no mechanism to add groups. It is possible to write methods specific to any function within a group. <p>The following table lists the functions for the different Groups. <dl> <dt>‘<samp><span class="samp">Math</span></samp>’<dd>abs, acos, acosh, asin, asinh, atan, atanh, ceiling, cos, cosh, cumsum, exp, floor, gamma, lgamma, log, log10, round, signif, sin, sinh, tan, tanh, trunc <br><dt>‘<samp><span class="samp">Summary</span></samp>’<dd>all, any, max, min, prod, range, sum <br><dt>‘<samp><span class="samp">Ops</span></samp>’<dd><code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>^</code>, <code><</code> , <code>></code>, <code><=</code>, <code>>=</code>, <code>!=</code>, <code>==</code>, <code>%%</code>, <code>%/%</code>, <code>&</code>, <code>|</code>, <code>!</code> </dl> <p>For operators in the Ops group a special method is invoked if the two operands taken together suggest a single method. Specifically, if both operands correspond to the same method or if one operand corresponds to a method that takes precedence over that of the other operand. If they do not suggest a single method then the default method is used. Either a group method or a class method dominates if the other operand has no corresponding method. A class method dominates a group method. <p>When the group is Ops the special variable <code>.Method</code> is a string vector with two elements. The elements of <code>.Method</code> are set to the name of the method if the corresponding argument is a member of the class that was used to determine the method. Otherwise the corresponding element of <code>.Method</code> is set to the zero length string, <code>""</code>. <div class="node"> <a name="Writing-methods"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Group-methods">Group methods</a>, Up: <a rel="up" accesskey="u" href="#Object_002doriented-programming">Object-oriented programming</a> </div> <h3 class="section">5.7 Writing methods</h3> <p>Users can easily write their own methods and generic functions. A <a name="index-function_002c-generic-205"></a>generic function is simply a function with a call to <code>UseMethod</code>. A method is simply a function that has been invoked via method dispatch. This can be as a result of a call to either <code>UseMethod</code> or <code>NextMethod</code>. <p>It is worth remembering that methods can be called directly. That means that they can be entered without a call to <code>UseMethod</code> having been made and hence the special variables <code>.Generic</code>, <code>.Class</code> and <code>.Method</code> will not have been instantiated. In that case the default rules detailed above will be used to determine these. <p>The most common use of <a name="index-function_002c-generic-206"></a>generic functions is to provide <code>print</code> and <code>summary</code> methods for statistical objects, generally the output of some model fitting process. To do this, each model attaches a class attribute to its output and then provides a special method that takes that output and provides a nice readable version of it. The user then needs only remember that <code>print</code> or <code>summary</code> will provide nice output for the results of any analysis. <!-- @node Modeling functions, Graphics model, Object-oriented programming, Top --> <!-- @chapter Modeling functions --> <!-- @node Graphics model, Computing on the language, Modeling functions, Top --> <!-- @chapter Graphics model --> <!-- @menu --> <!-- * Math expressions in text:: --> <!-- @end menu --> <!-- @node Math expressions in text, , Graphics model, Graphics model --> <!-- @section Math expressions in text --> <div class="node"> <a name="Computing-on-the-language"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#System-and-foreign-language-interfaces">System and foreign language interfaces</a>, Previous: <a rel="previous" accesskey="p" href="#Object_002doriented-programming">Object-oriented programming</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">6 Computing on the language</h2> <p>R belongs to a class of programming languages in which subroutines have the ability to modify or construct other subroutines and evaluate the result as an integral part of the language itself. This is similar to Lisp and Scheme and other languages of the “functional programming” variety, but in contrast to FORTRAN and the ALGOL family. The Lisp family takes this feature to the extreme by the “everything is a list” paradigm in which there is no distinction between programs and data. <p>R presents a friendlier interface to programming than Lisp does, at least to someone used to mathematical formulas and C-like control structures, but the engine is really very Lisp-like. R allows direct access to <a name="index-parsing-207"></a>parsed expressions and functions and allows you to alter and subsequently execute them, or create entirely new functions from scratch. <p>There is a number of standard applications of this facility, such as calculation of analytical derivatives of expressions, or the generation of polynomial functions from a vector of coefficients. However, there are also uses that are much more fundamental to the workings of the interpreted part of R. Some of these are essential to the reuse of functions as components in other functions, as the (admittedly not very pretty) calls to <code>model.frame</code> that are constructed in several modeling and plotting routines. Other uses simply allow elegant interfaces to useful functionality. As an example, consider the <code>curve</code> function, which allows you to draw the graph of a function given as an expression like <code>sin(x)</code> or the facilities for plotting mathematical expressions. <p>In this chapter, we give an introduction to the set of facilities that are available for computing on the language. <ul class="menu"> <li><a accesskey="1" href="#Direct-manipulation-of-language-objects">Direct manipulation of language objects</a> <li><a accesskey="2" href="#Substitutions">Substitutions</a> <li><a accesskey="3" href="#More-on-evaluation">More on evaluation</a> <li><a accesskey="4" href="#Evaluation-of-expression-objects">Evaluation of expression objects</a> <li><a accesskey="5" href="#Manipulation-of-function-calls">Manipulation of function calls</a> <li><a accesskey="6" href="#Manipulation-of-functions">Manipulation of functions</a> </ul> <div class="node"> <a name="Direct-manipulation-of-language-objects"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Substitutions">Substitutions</a>, Previous: <a rel="previous" accesskey="p" href="#Computing-on-the-language">Computing on the language</a>, Up: <a rel="up" accesskey="u" href="#Computing-on-the-language">Computing on the language</a> </div> <h3 class="section">6.1 Direct manipulation of language objects</h3> <p>There are three kinds of language objects that are available for modification, calls, expressions, and functions. At this point, we shall concentrate on the call objects. These are sometimes referred to as “unevaluated expressions”, although this terminology is somewhat confusing. The most direct method of obtaining a call object is to use <code>quote</code> with an expression argument, e.g., <pre class="example"> > e1 <- quote(2 + 2) > e2 <- quote(plot(x, y)) </pre> <p>The arguments are not evaluated, the result is simply the parsed argument. The objects <code>e1</code> and <code>e2</code> may be evaluated later using <code>eval</code>, or simply manipulated as data. It is perhaps most immediately obvious why the <code>e2</code> object has mode <code>"call"</code>, since it involves a call to the <code>plot</code> function with some arguments. However, <code>e1</code> actually has exactly the same structure as a call to the binary operator <code>+</code> with two arguments, a fact that gets clearly displayed by the following <pre class="example"> > quote("+"(2, 2)) 2 + 2 </pre> <p>The components of a call object are accessed using a list-like syntax, and may in fact be converted to and from lists using <code>as.list</code> and <code>as.call</code> <!-- FIXME man page for as.call says that this doesn't work, but it --> <!-- does... --> <pre class="example"> > e2[[1]] plot > e2[[2]] x > e2[[3]] y </pre> <p>When keyword argument matching is used, the keywords can be used as list tags: <pre class="example"> > e3 <- quote(plot(x = age, y = weight)) > e3$x age > e3$y weight </pre> <p>All the components of the call object have mode <code>"name"</code> in the preceding examples. This is true for identifiers in calls, but the components of a call can also be constants—which can be of any type, although the first component had better be a function if the call is to be evaluated successfully—or other call objects, corresponding to subexpressions. Objects of mode <a name="index-name-208"></a>name can be constructed from character strings using <code>as.name</code>, so one might modify the <code>e2</code> object as follows <pre class="example"> > e2[[1]] <- as.name("+") > e2 x + y </pre> <p>To illustrate the fact that subexpressions are simply components that are themselves calls, consider <pre class="example"> > e1[[2]] <- e2 > e1 x + y + 2 </pre> <p>All grouping parentheses in input are preserved in parsed expressions. They are represented as a function call with one argument, so that <code>4 - (2 - 2)</code> becomes <code>"-"(4, "(" ("-"(2, 2)))</code> in prefix notation. In evaluations, the ‘<samp><span class="samp">(</span></samp>’ operator just returns its argument. <p>This is a bit unfortunate, but it is not easy to write a <a name="index-parsing-209"></a>parser/deparser combination that both preserves user input, stores it in minimal form and ensures that parsing a deparsed expression gives the same expression back. <p>As it happens, R's parser is not perfectly invertible, nor is its deparser, as the following examples show <pre class="example"> > str(quote(c(1,2))) language c(1, 2) > str(c(1,2)) num [1:2] 1 2 > deparse(quote(c(1,2))) [1] "c(1, 2)" > deparse(c(1,2)) [1] "c(1, 2)" > quote("-"(2, 2)) 2 - 2 > quote(2 - 2) 2 - 2 </pre> <p class="noindent">Deparsed expressions should, however, evaluate to an equivalent value to the original expression (up to rounding error). <p>...internal storage of flow control constructs...note Splus incompatibility... <div class="node"> <a name="Substitutions"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#More-on-evaluation">More on evaluation</a>, Previous: <a rel="previous" accesskey="p" href="#Direct-manipulation-of-language-objects">Direct manipulation of language objects</a>, Up: <a rel="up" accesskey="u" href="#Computing-on-the-language">Computing on the language</a> </div> <h3 class="section">6.2 Substitutions</h3> <p>It is in fact not often that one wants to modify the innards of an expression like in the previous section. More frequently, one wants to simply get at an expression in order to deparse it and use it for labeling plots, for instance. An example of this is seen at the beginning of <code>plot.default</code>: <a name="index-substitute-210"></a> <pre class="example"> xlabel <- if (!missing(x)) deparse(substitute(x)) </pre> <p class="noindent">This causes the variable or expression given as the <code>x</code> argument to <code>plot</code> to be used for labeling the x-axis later on. <p>The function used to achieve this is <code>substitute</code> which takes the expression <code>x</code> and substitutes the expression that was passed through the formal argument <code>x</code>. Notice that for this to happen, <code>x</code> must carry information about the expression that creates its value. This is related to the <a name="index-evaluation_002c-lazy-211"></a>lazy evaluation scheme of R (see <a href="#Promise-objects">Promise objects</a>). A formal argument is really a <em>promise</em>, an object with three slots, one for the expression that defines it, one for the environment in which to evaluate that expression, and one for the value of that expression once evaluated. <code>substitute</code> will recognize a promise variable and substitute the value of its expression slot. If <code>substitute</code> is invoked inside a function, the local variables of the function are also subject to substitution. <p>The argument to <code>substitute</code> does not have to be a simple identifier, it can be an expression involving several variables and substitution will occur for each of these. Also, <code>substitute</code> has an additional argument which can be an environment or a list in which the variables are looked up. For example: <pre class="example"> > substitute(a + b, list(a = 1, b = quote(x))) 1 + x </pre> <p>Notice that quoting was necessary to substitute the <code>x</code>. This kind of construction comes in handy in connection with the facilities for putting math expression in graphs, as the following case shows <pre class="example"> > plot(0) > for (i in 1:4) + text(1, 0.2 * i, + substitute(x[ix] == y, list(ix = i, y = pnorm(i)))) </pre> <p>It is important to realize that the substitutions are purely lexical; there is no checking that the resulting call objects make sense if they are evaluated. <code>substitute(x <- x + 1, list(x = 2))</code> will happily return <code>2 <- 2 + 1</code>. However, some parts of R make up their own rules for what makes sense and what does not and might actually have a use for such ill-formed expressions. For example, using the “math in graphs” feature often involves constructions that are syntactically correct, but which would be meaningless to evaluate, like ‘<samp><span class="samp">{}>=40*" years"</span></samp>’. <p>Substitute will not evaluate its first argument. This leads to the puzzle of how to do substitutions on an object that is contained in a variable. The solution is to use <code>substitute</code> once more, like this <pre class="example"> > expr <- quote(x + y) > substitute(substitute(e, list(x = 3)), list(e = expr)) substitute(x + y, list(x = 3)) > eval(substitute(substitute(e, list(x = 3)), list(e = expr))) 3 + y </pre> <p>The exact rules for substitutions are as follows: Each <a name="index-symbol-212"></a>symbol in the <a name="index-parsing-213"></a>parse tree for the first is matched against the second argument, which can be a tagged list or an environment frame. If it is a simple local object, its value is inserted, <em>except</em> if matching against the global environment. If it is a promise (usually a function argument), the promise expression is substituted. If the symbol is not matched, it is left untouched. The special exception for substituting at the top level is admittedly peculiar. It has been inherited from S and the rationale is most likely that there is no control over which variables might be bound at that level so that it would be better to just make substitute act as <code>quote</code>. <p>The rule of promise substitution is slightly different from that of S if the local variable is modified before <code>substitute</code> is used. R will then use the new value of the variable, whereas S will unconditionally use the argument expression—unless it was a constant, which has the curious consequence that <code>f((1))</code> may be very different from <code>f(1)</code> in S. The R rule is considerably cleaner, although it does have consequences in connection with <a name="index-evaluation_002c-lazy-214"></a>lazy evaluation that comes as a surprise to some. Consider <pre class="example"> logplot <- function(y, ylab = deparse(substitute(y))) { y <- log(y) plot(y, ylab = ylab) } </pre> <p>This looks straightforward, but one will discover that the y label becomes an ugly <code>c(...)</code> expression. It happens because the rules of lazy evaluation causes the evaluation of the <code>ylab</code> expression to happen <em>after</em> <code>y</code> has been modified. The solution is to force <code>ylab</code> to be evaluated first, i.e., <pre class="example"> logplot <- function(y, ylab = deparse(substitute(y))) { ylab y <- log(y) plot(y, ylab = ylab) } </pre> <p>Notice that one should not use <code>eval(ylab)</code> in this situation. If <code>ylab</code> is a language or expression object, then that would cause the object to be evaluated as well, which would not at all be desirable if a math expression like <code>quote(log[e](y))</code> was being passed. <p>A variant on <code>substitute</code> is <code>bquote</code>, which is used to replace some subexpressions with their values. The example from above <pre class="example"> > plot(0) > for (i in 1:4) + text(1, 0.2 * i, + substitute(x[ix] == y, list(ix = i, y = pnorm(i)))) </pre> <p>could be written more compactly as <pre class="example"> plot(0) for(i in 1:4) text(1, 0.2*i, bquote( x[.(i)] == .(pnorm(i)) )) </pre> <p>The expression is quoted except for the contents of <code>.()</code> subexpressions, which are replaced with their values. There is an optional argument to compute the values in a different environment. The syntax for <code>bquote</code> is borrowed from the LISP backquote macro. <div class="node"> <a name="More-on-evaluation"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Evaluation-of-expression-objects">Evaluation of expression objects</a>, Previous: <a rel="previous" accesskey="p" href="#Substitutions">Substitutions</a>, Up: <a rel="up" accesskey="u" href="#Computing-on-the-language">Computing on the language</a> </div> <h3 class="section">6.3 More on evaluation</h3> <p><a name="index-evaluation-215"></a>The <code>eval</code> function was introduced earlier in this chapter as a means of evaluating call objects. However, this is not the full story. It is also possible to specify the <a name="index-environment-216"></a>environment in which the evaluation is to take place. By default this is the evaluation frame from which <code>eval</code> is called, but quite frequently it needs to be set to something else. <a name="index-eval-217"></a> Very often, the relevant evaluation frame is that of the parent of the current frame (cf. ???). In particular, when the object to evaluate is the result of a <code>substitute</code> operation of the function arguments, it will contain variables that make sense to the caller only (notice that there is no reason to expect that the variables of the caller are in the <a name="index-scope-218"></a>lexical scope of the callee). Since evaluation in the parent frame occurs frequently, an <code>eval.parent</code> function exists as a shorthand for <code>eval(expr, sys.frame(sys.parent()))</code>. <p>Another case that occurs frequently is evaluation in a list or a data frame. For instance, this happens in connection with the <code>model.frame</code> function when a <code>data</code> argument is given. Generally, the terms of the model formula need to be evaluated in <code>data</code>, but they may occasionally also contain references to items in the caller of <code>model.frame</code>. This is sometimes useful in connection with simulation studies. So for this purpose one needs not only to evaluate an expression in a list, but also to specify an enclosure into which the search continues if the variable is not in the list. Hence, the call has the form <pre class="example"> eval(expr, data, sys.frame(sys.parent())) </pre> <p>Notice that evaluation in a given environment may actually change that environment, most obviously in cases involving the <a name="index-assignment-219"></a>assignment operator, such as <pre class="example"> eval(quote(total <- 0), environment(robert$balance)) # <span class="roman">rob Rob</span> </pre> <p class="noindent">This is also true when evaluating in lists, but the original list does not change because one is really working on a copy. <div class="node"> <a name="Evaluation-of-expression-objects"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Manipulation-of-function-calls">Manipulation of function calls</a>, Previous: <a rel="previous" accesskey="p" href="#More-on-evaluation">More on evaluation</a>, Up: <a rel="up" accesskey="u" href="#Computing-on-the-language">Computing on the language</a> </div> <h3 class="section">6.4 Evaluation of expression objects</h3> <p>Objects of mode <code>"expression"</code> are defined in <a href="#Expression-objects">Expression objects</a>. They are very similar to lists of call objects. <pre class="example"> > ex <- expression(2 + 2, 3 + 4) > ex[[1]] 2 + 2 > ex[[2]] 3 + 4 > eval(ex) [1] 7 </pre> <p>Notice that evaluating an expression object evaluates each call in turn, but the final value is that of the last call. In this respect it behaves almost identically to the compound language object <code>quote({2 + 2; 3 + 4})</code>. However, there is a subtle difference: Call objects are indistinguishable from subexpressions in a parse tree. This means that they are automatically evaluated in the same way a subexpression would be. Expression objects can be recognized during evaluation and in a sense retain their quotedness. The evaluator will not evaluate an expression object recursively, only when it is passed directly to <code>eval</code> function as above. The difference can be seen like this: <pre class="example"> > eval(substitute(mode(x), list(x = quote(2 + 2)))) [1] "numeric" > eval(substitute(mode(x), list(x = expression(2 + 2)))) [1] "expression" </pre> <p>The deparser represents an expression object by the call that creates it. This is similar to the way it handles numerical vectors and several other objects that do not have a specific external representation. However, it does lead to the following bit of confusion: <pre class="example"> > e <- quote(expression(2 + 2)) > e expression(2 + 2) > mode(e) [1] "call" > ee <- expression(2 + 2) > ee expression(2 + 2) > mode(ee) [1] "expression" </pre> <p class="noindent">I.e., <code>e</code> and <code>ee</code> look identical when printed, but one is a call that generates an expression object and the other is the object itself. <div class="node"> <a name="Manipulation-of-function-calls"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Manipulation-of-functions">Manipulation of functions</a>, Previous: <a rel="previous" accesskey="p" href="#Evaluation-of-expression-objects">Evaluation of expression objects</a>, Up: <a rel="up" accesskey="u" href="#Computing-on-the-language">Computing on the language</a> </div> <h3 class="section">6.5 Manipulation of function calls</h3> <p>It is possible for a <a name="index-function-220"></a>function to find out how it has been called by looking at the result of <code>sys.call</code> as in the following example of a function that simply returns its own call: <pre class="example"> > f <- function(x, y, ...) sys.call() > f(y = 1, 2, z = 3, 4) f(y = 1, 2, z = 3, 4) </pre> <p>However, this is not really useful except for debugging because it requires the function to keep track of argument matching in order to interpret the call. For instance, it must be able to see that the 2nd actual argument gets matched to the first formal one (<code>x</code> in the above example). <p>More often one requires the call with all actual arguments bound to the corresponding formals. To this end, the function <code>match.call</code> is used. Here's a variant of the preceding example, a function that returns its own call with arguments matched <pre class="example"> > f <- function(x, y, ...) match.call() > f(y = 1, 2, z = 3, 4) f(x = 2, y = 1, z = 3, 4) </pre> <p>Notice that the second argument now gets matched to <code>x</code> and appears in the corresponding position in the result. <p>The primary use of this technique is to call another function with the same arguments, possibly deleting some and adding others. A typical application is seen at the start of the <code>lm</code> function: <pre class="example"> mf <- cl <- match.call() mf$singular.ok <- mf$model <- mf$method <- NULL mf$x <- mf$y <- mf$qr <- mf$contrasts <- NULL mf$drop.unused.levels <- TRUE mf[[1]] <- as.name("model.frame") mf <- eval(mf, sys.frame(sys.parent())) </pre> <p>Notice that the resulting call is <a name="index-evaluation-221"></a>evaluated in the parent frame, in which one can be certain that the involved expressions make sense. The call can be treated as a list object where the first element is the name of the function and the remaining elements are the actual argument expressions, with the corresponding formal argument names as tags. Thus, the technique to eliminate undesired arguments is to assign <code>NULL</code>, as seen in lines 2 and 3, and to add an argument one uses tagged list <a name="index-assignment-222"></a>assignment (here to pass <code>drop.unused.levels = TRUE</code>) as in line 4. To change the name of the function called, assign to the first element of the list and make sure that the value is a name, either using the <code>as.name("model.frame")</code> construction here or <code>quote(model.frame)</code>. <p>The <code>match.call</code> function has an <code>expand.dots</code> argument which is a switch which if set to <code>FALSE</code> lets all ‘<samp><span class="samp">...</span></samp>’ arguments be collected as a single argument with the tag ‘<samp><span class="samp">...</span></samp>’. <a name="index-match_002ecall-223"></a> <pre class="example"> > f <- function(x, y, ...) match.call(expand.dots = FALSE) > f(y = 1, 2, z = 3, 4) f(x = 2, y = 1, ... = list(z = 3, 4)) </pre> <p>The ‘<samp><span class="samp">...</span></samp>’ argument is a list (a pairlist to be precise), not a call to <code>list</code> like it is in S: <pre class="example"> > e1 <- f(y = 1, 2, z = 3, 4)$... > e1 $z [1] 3 [[2]] [1] 4 </pre> <p>One reason for using this form of <code>match.call</code> is simply to get rid of any ‘<samp><span class="samp">...</span></samp>’ arguments in order not to be passing unspecified arguments on to functions that may not know them. Here's an example paraphrased from <code>plot.formula</code>: <pre class="example"> m <- match.call(expand.dots = FALSE) m$... <- NULL m[[1]] <- "model.frame" </pre> <p>A more elaborate application is in <code>update.default</code> where a set of optional extra arguments can add to, replace, or cancel those of the original call: <pre class="example"> extras <- match.call(expand.dots = FALSE)$... if (length(extras) > 0) { existing <- !is.na(match(names(extras), names(call))) for (a in names(extras)[existing]) call[[a]] <- extras[[a]] if (any(!existing)) { call <- c(as.list(call), extras[!existing]) call <- as.call(call) } } </pre> <p>Notice that care is taken to modify existing arguments individually in case <code>extras[[a]] == NULL</code>. Concatenation does not work on call objects without the coercion as shown; this is arguably a bug. <p>Two further functions exist for the construction of function calls, namely <code>call</code> and <code>do.call</code>. <p>The function <code>call</code> allows creation of a call object from the function name and the list of arguments <pre class="example"> > x <- 10.5 > call("round", x) round(10.5) </pre> <p>As seen, the value of <code>x</code> rather than the <a name="index-symbol-224"></a>symbol is inserted in the call, so it is distinctly different from <code>round(x)</code>. The form is used rather rarely, but is occasionally useful where the name of a function is available as a character variable. <p>The function <code>do.call</code> is related, but evaluates the call immediately and takes the arguments from an object of mode <code>"list"</code> containing all the arguments. A natural use of this is when one wants to apply a function like <code>cbind</code> to all elements of a list or data frame. <a name="index-do_002ecall-225"></a> <pre class="example"> is.na.data.frame <- function (x) { y <- do.call("cbind", lapply(x, "is.na")) rownames(y) <- row.names(x) y } </pre> <p>Other uses include variations over constructions like <code>do.call("f", list(...))</code>. However, one should be aware that this involves evaluation of the arguments before the actual function call, which may defeat aspects of lazy evaluation and argument substitution in the function itself. A similar remark applies to the <code>call</code> function. <div class="node"> <a name="Manipulation-of-functions"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Manipulation-of-function-calls">Manipulation of function calls</a>, Up: <a rel="up" accesskey="u" href="#Computing-on-the-language">Computing on the language</a> </div> <h3 class="section">6.6 Manipulation of functions</h3> <p>It is often useful to be able to manipulate the components of a <a name="index-function-226"></a>function or closure. R provides a set of interface functions for this purpose. <dl> <dt><code>body</code><a name="index-body-227"></a><dd>Returns the expression that is the body of the function. <br><dt><code>formals</code><a name="index-formals-228"></a><dd>Returns a list of the formal arguments to the function. This is a <code>pairlist</code>. <br><dt><code>environment</code><a name="index-environment-229"></a><dd><a name="index-environment-230"></a>Returns the environment associated with the function. <br><dt><code>body<-</code><a name="index-body_003c_002d-231"></a><dd>This sets the body of the function to the supplied expression. <br><dt><code>formals<-</code><a name="index-formals_003c_002d-232"></a><dd>Sets the formal arguments of the function to the supplied list. <br><dt><code>environment<-</code><a name="index-environment_003c_002d-233"></a><dd>Sets the environment of the function to the specified environment. </dl> <p>It is also possible to alter the bindings of different variables in the environment of the function, using code along the lines of <code>evalq(x <- 5, environment(f))</code>. <p>It is also possible to convert a <a name="index-function-234"></a>function to a list using <code>as.list</code>. The result is the concatenation of the list of formal arguments with the function body. Conversely such a list can be converted to a function using <code>as.function</code>. This functionality is mainly included for S compatibility. Notice that environment information is lost when <code>as.list</code> is used, whereas <code>as.function</code> has an argument that allows the environment to be set. <div class="node"> <a name="System-and-foreign-language-interfaces"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Exception-handling">Exception handling</a>, Previous: <a rel="previous" accesskey="p" href="#Computing-on-the-language">Computing on the language</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">7 System and foreign language interfaces</h2> <ul class="menu"> <li><a accesskey="1" href="#Operating-system-access">Operating system access</a> <li><a accesskey="2" href="#Foreign-language-interfaces">Foreign language interfaces</a> <li><a accesskey="3" href="#g_t_002eInternal-and-_002ePrimitive">.Internal and .Primitive</a> </ul> <div class="node"> <a name="Operating-system-access"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Foreign-language-interfaces">Foreign language interfaces</a>, Previous: <a rel="previous" accesskey="p" href="#System-and-foreign-language-interfaces">System and foreign language interfaces</a>, Up: <a rel="up" accesskey="u" href="#System-and-foreign-language-interfaces">System and foreign language interfaces</a> </div> <h3 class="section">7.1 Operating system access</h3> <p>Access to the operating system shell is via the R function <code>system</code>. <a name="index-system-235"></a>The details will differ by platform (see the on-line help), and about all that can safely be assumed is that the first argument will be a string <code>command</code> that will be passed for execution (not necessarily by a shell) and the second argument will be <code>internal</code> which if true will collect the output of the command into an R character vector. <p>The functions <code>system.time</code> <a name="index-system_002etime-236"></a>and <code>proc.time</code> <a name="index-proc_002etime-237"></a>are available for timing (although the information available may be limited on non-Unix-like platforms). <p>Information from the operating system <a name="index-environment-238"></a>environment can be accessed and manipulated with <blockquote> <p><table summary=""><tr align="left"><td valign="top" width="30%"><code>Sys.getenv</code> </td><td valign="top" width="70%">OS environment variables <a name="index-Sys_002egetenv-239"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>Sys.putenv</code> <a name="index-Sys_002eputenv-240"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>Sys.getlocale</code> </td><td valign="top" width="70%">System locale <a name="index-Sys_002egetlocale-241"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>Sys.putlocale</code> <a name="index-Sys_002eputlocale-242"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>Sys.localeconv</code> <a name="index-Sys_002elocaleconv-243"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>Sys.time</code> </td><td valign="top" width="70%">Current time <a name="index-Sys_002etime-244"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>Sys.timezone</code> </td><td valign="top" width="70%">Time zone <a name="index-Sys_002etimezone-245"></a> <br></td></tr></table> </blockquote> <p>A uniform set of file access functions is provided on all platforms: <blockquote> <p><table summary=""><tr align="left"><td valign="top" width="30%"><code>file.access</code> </td><td valign="top" width="70%">Ascertain File Accessibility <a name="index-file_002eaccess-246"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>file.append</code> </td><td valign="top" width="70%">Concatenate files <a name="index-file_002eappend-247"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>file.choose</code> </td><td valign="top" width="70%">Prompt user for file name <a name="index-file_002echoose-248"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>file.copy</code> </td><td valign="top" width="70%">Copy files <a name="index-file_002ecopy-249"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>file.create</code> </td><td valign="top" width="70%">Create or truncate a files <a name="index-file_002ecreate-250"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>file.exists</code> </td><td valign="top" width="70%">Test for existence <a name="index-file_002eexists-251"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>file.info</code> </td><td valign="top" width="70%">Miscellaneous file information <a name="index-file_002einfo-252"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>file.remove</code> </td><td valign="top" width="70%">remove files <a name="index-file_002eremove-253"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>file.rename</code> </td><td valign="top" width="70%">rename files <a name="index-file_002erename-254"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>file.show</code> </td><td valign="top" width="70%">Display a text file <a name="index-file_002eshow-255"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>unlink</code> </td><td valign="top" width="70%">Remove files or directories. <a name="index-unlink-256"></a> <br></td></tr></table> </blockquote> <p>There are also functions for manipulating file names and paths in a platform-independent way. <blockquote> <p><table summary=""><tr align="left"><td valign="top" width="30%"><code>basename</code> </td><td valign="top" width="70%">File name without directory <a name="index-basename-257"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>dirname</code> </td><td valign="top" width="70%">Directory name <a name="index-dirname-258"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>file.path</code> </td><td valign="top" width="70%">Construct path to file <a name="index-file_002epath-259"></a><br></td></tr><tr align="left"><td valign="top" width="30%"><code>path.expand</code> </td><td valign="top" width="70%">Expand <code>~</code> in Unix path <a name="index-path_002eexpand-260"></a> <br></td></tr></table> </blockquote> <div class="node"> <a name="Foreign-language-interfaces"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#g_t_002eInternal-and-_002ePrimitive">.Internal and .Primitive</a>, Previous: <a rel="previous" accesskey="p" href="#Operating-system-access">Operating system access</a>, Up: <a rel="up" accesskey="u" href="#System-and-foreign-language-interfaces">System and foreign language interfaces</a> </div> <h3 class="section">7.2 Foreign language interfaces</h3> <p><a name="index-g_t_002eC-261"></a><a name="index-g_t_002eFortran-262"></a><a name="index-g_t_002eCall-263"></a><a name="index-g_t_002eExternal-264"></a> See <a href="R-exts.html#System-and-foreign-language-interfaces">System and foreign language interfaces</a> for the details of adding functionality to R via compiled code. <p>Functions <code>.C</code> and <code>.Fortran</code> provide a standard interface to compiled code that has been linked into R, either at build time or via <code>dyn.load</code>. They are primarily intended for compiled <strong>C</strong> and FORTRAN code respectively, but the <code>.C</code> function can be used with other languages which can generate C interfaces, for example C++. <p>Functions <code>.Call</code> and <code>.External</code> provide interfaces which allow compiled code (primarily compiled <strong>C</strong> code) to manipulate R objects. <div class="node"> <a name=".Internal-and-.Primitive"></a> <a name="g_t_002eInternal-and-_002ePrimitive"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Foreign-language-interfaces">Foreign language interfaces</a>, Up: <a rel="up" accesskey="u" href="#System-and-foreign-language-interfaces">System and foreign language interfaces</a> </div> <h3 class="section">7.3 .Internal and .Primitive</h3> <p><a name="index-g_t_002eInternal-265"></a><a name="index-g_t_002ePrimitive-266"></a> The <code>.Internal</code> and <code>.Primitive</code> interfaces are used to call <strong>C</strong> code compiled into R at build time. See <a href="R-ints.html#g_t_002eInternal-vs-_002ePrimitive">.Internal vs .Primitive</a>. <div class="node"> <a name="Exception-handling"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Debugging">Debugging</a>, Previous: <a rel="previous" accesskey="p" href="#System-and-foreign-language-interfaces">System and foreign language interfaces</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">8 Exception handling</h2> <p>The exception handling facilities in R are provided through two mechanisms. Functions such as <code>stop</code> or <code>warning</code> can be called directly or options such as <code>"warn"</code> can be used to control the handling of problems. <ul class="menu"> <li><a accesskey="1" href="#stop">stop</a> <li><a accesskey="2" href="#warning">warning</a> <li><a accesskey="3" href="#on_002eexit">on.exit</a> <li><a accesskey="4" href="#Error-options">Error options</a> </ul> <div class="node"> <a name="stop"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#warning">warning</a>, Previous: <a rel="previous" accesskey="p" href="#Exception-handling">Exception handling</a>, Up: <a rel="up" accesskey="u" href="#Exception-handling">Exception handling</a> </div> <h3 class="section">8.1 stop</h3> <p><a name="index-stop-267"></a> A call to <code>stop</code> halts the evaluation of the current expression, prints the message argument and returns execution to top-level. <div class="node"> <a name="warning"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#on_002eexit">on.exit</a>, Previous: <a rel="previous" accesskey="p" href="#stop">stop</a>, Up: <a rel="up" accesskey="u" href="#Exception-handling">Exception handling</a> </div> <h3 class="section">8.2 warning</h3> <p><a name="index-warning-268"></a><a name="index-warnings-269"></a> The function <code>warning</code> takes a single argument that is a character string. The behaviour of a call to <code>warning</code> depends on the value of the option <code>"warn"</code>. If <code>"warn"</code> is negative warnings are ignored. If it is zero, they are stored and printed after the top-level function has completed. If it is one, they are printed as they occur and if it is 2 (or larger) warnings are turned into errors. <p>If <code>"warn"</code> is zero (the default), a variable <code>last.warning</code> is created and the messages associated with each call to <code>warning</code> are stored, sequentially, in this vector. If there are fewer than 10 warnings they are printed after the function has finished evaluating. If there are more than 10 then a message indicating how many warnings occurred is printed. In either case <code>last.warning</code> contains the vector of messages, and <code>warnings</code> provides a way to access and print it. <div class="node"> <a name="on.exit"></a> <a name="on_002eexit"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Error-options">Error options</a>, Previous: <a rel="previous" accesskey="p" href="#warning">warning</a>, Up: <a rel="up" accesskey="u" href="#Exception-handling">Exception handling</a> </div> <h3 class="section">8.3 on.exit</h3> <p><a name="index-on_002eexit-270"></a> A function can insert a call to <code>on.exit</code> at any point in the body of a function. The effect of a call to <code>on.exit</code> is to store the value of the body so that it will be executed when the function exits. This allows the function to change some system parameters and to ensure that they are reset to appropriate values when the function is finished. The <code>on.exit</code> is guaranteed to be executed when the function exits either directly or as the result of a warning. <p>An error in the evaluation of the <code>on.exit</code> code causes an immediate jump to top-level without further processing of the <code>on.exit</code> code. <p><code>on.exit</code> takes a single argument which is an expression to be evaluated when the function is exited. <!-- @node restart, Error options, on.exit, Exception handling --> <!-- @section restart --> <!-- @findex restart --> <!-- A call to @code{restart} effectively makes the function a possible point --> <!-- of return if an error occurs during the evaluation of that function (or --> <!-- one of the functions it calls). --> <!-- @code{restart} takes a single argument which is a logical variable. If --> <!-- the value of the logical is @code{TRUE} then a jump-point is --> <!-- established. If the value is @code{FALSE} then the jump-point is --> <!-- removed. --> <!-- When a jump is executed the jump-point is removed. --> <!-- When an error occurs and one or more jump points are active then control --> <!-- is returned to the innermost function that has a jump-point established. --> <!-- Execution begins with the first statement in the body of the selected --> <!-- function. The --> <!-- @cindex environment --> <!-- environment for subsequent --> <!-- @cindex evaluation --> <!-- evaluation is the environment --> <!-- that was in effect at the time that the error that triggered the jump --> <!-- was signalled. --> <div class="node"> <a name="Error-options"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#on_002eexit">on.exit</a>, Up: <a rel="up" accesskey="u" href="#Exception-handling">Exception handling</a> </div> <h3 class="section">8.4 Error options</h3> <p>There are a number of <code>options</code> variables that can be used to control how R handles errors and warnings. The are listed in the table below. <dl> <dt>‘<samp><span class="samp">warn</span></samp>’<dd>Controls the printing of warnings. <br><dt>‘<samp><span class="samp">warning.expression</span></samp>’<dd>Sets an expression that is to be evaluated when a warning occurs. The normal printing of warnings is suppressed if this option is set. <br><dt>‘<samp><span class="samp">error</span></samp>’<dd>Installs an expression that will be evaluated when an error occurs. The normal printing of error messages and warning messages precedes the evaluation of the expression. </dl> <p>Expressions installed by <code>options("error")</code> are evaluated before calls to <code>on.exit</code> are carried out. <p>One can use <code>options(error = expression(q("yes")))</code> to get R to quit when an error has been signalled. In this case an error will cause R to shut down and the global environment will be saved. <div class="node"> <a name="Debugging"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Parser">Parser</a>, Previous: <a rel="previous" accesskey="p" href="#Exception-handling">Exception handling</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">9 Debugging</h2> <p>Debugging code has always been a bit of an art. R provides several tools that help users find problems in their code. These tools halt execution at particular points in the code and the current state of the computation can be inspected. <p>Most debugging takes place either through calls to <code>browser</code> or <code>debug</code>. Both of these functions rely on the same internal mechanism and both provide the user with a special prompt. Any command can be typed at the prompt. The evaluation <a name="index-environment-271"></a>environment for the command is the currently active environment. This allows you to examine the current state of any variables etc. <p>There are five special commands that R interprets differently. They are, <dl> <dt>‘<samp><span class="samp"><RET></span></samp>’<dd>Go to the next statement if the function is being debugged. Continue execution if the browser was invoked. <br><dt>‘<samp><span class="samp">c</span></samp>’<dt>‘<samp><span class="samp">cont</span></samp>’<dd>Continue the execution. <br><dt>‘<samp><span class="samp">n</span></samp>’<dd>Execute the next statement in the function. This works from the browser as well. <br><dt>‘<samp><span class="samp">where</span></samp>’<dd>Show the call stack <br><dt>‘<samp><span class="samp">Q</span></samp>’<dd>Halt execution and jump to the top-level immediately. </dl> <p><a name="index-name-272"></a>If there is a local variable with the same name as one of the special commands listed above then its value can be accessed by using <code>get</code>. A call to <code>get</code> with the name in quotes will retrieve the value in the current <a name="index-environment-273"></a>environment. <p>The debugger provides access only to interpreted expressions. If a function calls a foreign language (such as <strong>C</strong>) then no access to the statements in that language is provided. Execution will halt on the next statement that is evaluated in R. A symbolic debugger such as <code>gdb</code> can be used to debug compiled code. <ul class="menu"> <li><a accesskey="1" href="#browser">browser</a> <li><a accesskey="2" href="#debug_002fundebug">debug/undebug</a> <li><a accesskey="3" href="#trace_002funtrace">trace/untrace</a> <li><a accesskey="4" href="#traceback">traceback</a> </ul> <div class="node"> <a name="browser"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#debug_002fundebug">debug/undebug</a>, Previous: <a rel="previous" accesskey="p" href="#Debugging">Debugging</a>, Up: <a rel="up" accesskey="u" href="#Debugging">Debugging</a> </div> <h3 class="section">9.1 browser</h3> <p><a name="index-browser-274"></a> A call to the function <code>browser</code> causes R to halt execution at that point and to provide the user with a special prompt. Arguments to <code>browser</code> are ignored. <pre class="example"> > foo <- function(s) { + c <- 3 + browser() + } > foo(4) Called from: foo(4) Browse[1]> s [1] 4 Browse[1]> get("c") [1] 3 Browse[1]> </pre> <div class="node"> <a name="debug%2fundebug"></a> <a name="debug_002fundebug"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#trace_002funtrace">trace/untrace</a>, Previous: <a rel="previous" accesskey="p" href="#browser">browser</a>, Up: <a rel="up" accesskey="u" href="#Debugging">Debugging</a> </div> <h3 class="section">9.2 debug/undebug</h3> <p><a name="index-debug-275"></a><a name="index-undebug-276"></a> The debugger can be invoked on any function by using the command <code>debug(</code><var>fun</var><code>)</code>. Subsequently, each time that function is evaluated the debugger is invoked. The debugger allows you to control the evaluation of the statements in the body of the function. Before each statement is executed the statement is printed out and a special prompt provided. Any command can be given, those in the table above have special meaning. <p>Debugging is turned off by a call to <code>undebug</code> with the function as an argument. <pre class="example"> > debug(mean.default) > mean(1:10) debugging in: mean.default(1:10) debug: { if (na.rm) x <- x[!is.na(x)] trim <- trim[1] n <- length(c(x, recursive = TRUE)) if (trim > 0) { if (trim >= 0.5) return(median(x, na.rm = FALSE)) lo <- floor(n * trim) + 1 hi <- n + 1 - lo x <- sort(x, partial = unique(c(lo, hi)))[lo:hi] n <- hi - lo + 1 } sum(x)/n } Browse[1]> debug: if (na.rm) x <- x[!is.na(x)] Browse[1]> debug: trim <- trim[1] Browse[1]> debug: n <- length(c(x, recursive = TRUE)) Browse[1]> c exiting from: mean.default(1:10) [1] 5.5 </pre> <div class="node"> <a name="trace%2funtrace"></a> <a name="trace_002funtrace"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#traceback">traceback</a>, Previous: <a rel="previous" accesskey="p" href="#debug_002fundebug">debug/undebug</a>, Up: <a rel="up" accesskey="u" href="#Debugging">Debugging</a> </div> <h3 class="section">9.3 trace/untrace</h3> <p><a name="index-trace-277"></a><a name="index-untrace-278"></a> Another way of monitoring the behaviour of R is through the <code>trace</code> mechanism. <code>trace</code> is called with a single argument that is the name of the function you want to trace. The name does not need to be quoted but for some functions you will need to quote the name in order to avoid a syntax error. <p>When <code>trace</code> has been invoked on a function then every time that function is evaluated the call to it is printed out. This mechanism is removed by calling <code>untrace</code> with the function as an argument. <pre class="example"> > trace("[<-") > x <- 1:10 > x[3] <- 4 trace: "[<-"(*tmp*, 3, value = 4) </pre> <div class="node"> <a name="traceback"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#trace_002funtrace">trace/untrace</a>, Up: <a rel="up" accesskey="u" href="#Debugging">Debugging</a> </div> <h3 class="section">9.4 traceback</h3> <p><a name="index-traceback-279"></a> When an error has caused a jump to top-level a special variable called <code>.Traceback</code> is placed into the base environment. <code>.Traceback</code> is a character vector with one entry for each function call that was active at the time the error occurred. An examination of <code>.Traceback</code> can be carried out by a call to <code>traceback</code>. <div class="node"> <a name="Parser"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Function-and-Variable-Index">Function and Variable Index</a>, Previous: <a rel="previous" accesskey="p" href="#Debugging">Debugging</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="chapter">10 Parser</h2> <p><a name="index-parsing-280"></a> The parser is what converts the textual representation of R code into an internal form which may then be passed to the R evaluator which causes the specified instructions to be carried out. The internal form is itself an R object and can be saved and otherwise manipulated within the R system. <ul class="menu"> <li><a accesskey="1" href="#The-parsing-process">The parsing process</a> <li><a accesskey="2" href="#Comments">Comments</a> <li><a accesskey="3" href="#Tokens">Tokens</a> <li><a accesskey="4" href="#Expressions">Expressions</a> <li><a accesskey="5" href="#Directives">Directives</a> </ul> <div class="node"> <a name="The-parsing-process"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Comments">Comments</a>, Previous: <a rel="previous" accesskey="p" href="#Parser">Parser</a>, Up: <a rel="up" accesskey="u" href="#Parser">Parser</a> </div> <!-- node-name, next, previous, up --> <h3 class="section">10.1 The parsing process</h3> <ul class="menu"> <li><a accesskey="1" href="#Modes-of-parsing">Modes of parsing</a> <li><a accesskey="2" href="#Internal-representation">Internal representation</a> <li><a accesskey="3" href="#Deparsing">Deparsing</a> </ul> <div class="node"> <a name="Modes-of-parsing"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Internal-representation">Internal representation</a>, Previous: <a rel="previous" accesskey="p" href="#The-parsing-process">The parsing process</a>, Up: <a rel="up" accesskey="u" href="#The-parsing-process">The parsing process</a> </div> <!-- node-name, next, previous, up --> <h4 class="subsection">10.1.1 Modes of parsing</h4> <p>Parsing in R occurs in three different variants: <ul> <li>The read-eval-print loop <li>Parsing of text files <li>Parsing of character strings </ul> <p>The read-eval-print loop forms the basic command line interface to R. Textual input is read until a complete R expression is available. Expressions may be split over several input lines. The primary prompt (by default ‘<samp><span class="samp">> </span></samp>’) indicates that the parser is ready for a new expression, and a continuation prompt (by default ‘<samp><span class="samp">+ </span></samp>’) indicates that the parser expects the remainder of an incomplete expression. The expression is converted to internal form during input and the parsed expression is passed to the evaluator and the result is printed (unless specifically made invisible). If the parser finds itself in a state which is incompatible with the language syntax, a “Syntax Error” is flagged and the parser resets itself and resumes input at the beginning of the next input line. <p>Text files can be parsed using the <code>parse</code> function. In particular, this is done during execution of the <code>source</code> function, which allows commands to be stored in an external file and executed as if they had been typed at the keyboard. Note, though, that the entire file is parsed and syntax checked before any evaluation takes place. <p>Character strings, or vectors thereof, can be parsed using the <code>text=</code> argument to <code>parse</code>. The strings are treated exactly as if they were the lines of an input file. <div class="node"> <a name="Internal-representation"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Deparsing">Deparsing</a>, Previous: <a rel="previous" accesskey="p" href="#Modes-of-parsing">Modes of parsing</a>, Up: <a rel="up" accesskey="u" href="#The-parsing-process">The parsing process</a> </div> <!-- node-name, next, previous, up --> <h4 class="subsection">10.1.2 Internal representation</h4> <p><a name="index-parsing-281"></a>Parsed expressions are stored in an R object containing the parse tree. A fuller description of such objects can be found in <a href="#Language-objects">Language objects</a> and <a href="#Expression-objects">Expression objects</a>. Briefly, every elementary R expression is stored in <a name="index-function-282"></a>function call form, as a list with the first element containing the function name and the remainder containing the arguments, which may in turn be further R expressions. The list elements can be named, corresponding to tagged matching of formal and actual arguments. Note that <em>all</em> R syntax elements are treated in this way, e.g. the assignment <code>x <- 1</code> is encoded as <code>"<-"(x, 1)</code>. <div class="node"> <a name="Deparsing"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Internal-representation">Internal representation</a>, Up: <a rel="up" accesskey="u" href="#The-parsing-process">The parsing process</a> </div> <!-- node-name, next, previous, up --> <h4 class="subsection">10.1.3 Deparsing</h4> <p>Any R object can be converted to an R expression using <code>deparse</code>. This is frequently used in connection with output of results, e.g. for labeling plots. Notice that only objects of mode <code>"expression"</code> can be expected to be unchanged by reparsing the output of deparsing. For instance, the numeric vector <code>1:5</code> will deparse as <code>"c(1, 2, 3, 4, 5)"</code>, which will reparse as a call to the function <code>c</code>. As far as possible, evaluating the deparsed and reparsed expression gives the same result as evaluating the original, but there are a couple of awkward exceptions, mostly involving expressions that weren't generated from a textual representation in the first place. <div class="node"> <a name="Comments"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Tokens">Tokens</a>, Previous: <a rel="previous" accesskey="p" href="#The-parsing-process">The parsing process</a>, Up: <a rel="up" accesskey="u" href="#Parser">Parser</a> </div> <!-- node-name, next, previous, up --> <h3 class="section">10.2 Comments</h3> <p><a name="index-comments-283"></a>Comments in R are ignored by the parser. Any text from a <a name="index-g_t_0040code_007b_0023_007d-284"></a><code>#</code> character to the end of the line is taken to be a comment, unless the <code>#</code> character is inside a quoted string. For example, <pre class="example"> > x <- 1 # This is a comment... > y <- " #... but this is not." </pre> <div class="node"> <a name="Tokens"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Expressions">Expressions</a>, Previous: <a rel="previous" accesskey="p" href="#Comments">Comments</a>, Up: <a rel="up" accesskey="u" href="#Parser">Parser</a> </div> <!-- node-name, next, previous, up --> <h3 class="section">10.3 Tokens</h3> <p>Tokens are the elementary building blocks of a programming language. They are recognised during <em>lexical analysis</em> which (conceptually, at least) takes place prior to the syntactic analysis performed by the parser itself. <ul class="menu"> <li><a accesskey="1" href="#Literal-constants">Literal constants</a> <li><a accesskey="2" href="#Identifiers">Identifiers</a> <li><a accesskey="3" href="#Reserved-words">Reserved words</a> <li><a accesskey="4" href="#Special-operators">Special operators</a> <li><a accesskey="5" href="#Separators">Separators</a> <li><a accesskey="6" href="#Operator-tokens">Operator tokens</a> <li><a accesskey="7" href="#Grouping">Grouping</a> <li><a accesskey="8" href="#Indexing-tokens">Indexing tokens</a> </ul> <div class="node"> <a name="Literal-constants"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Identifiers">Identifiers</a>, Previous: <a rel="previous" accesskey="p" href="#Tokens">Tokens</a>, Up: <a rel="up" accesskey="u" href="#Tokens">Tokens</a> </div> <!-- node-name, next, previous, up --> <h4 class="subsection">10.3.1 Constants</h4> <p>There are five types of constants: integer, logical, numeric, complex and string. <p>In addition, there are four special constants, <code>NULL</code>, <code>NA</code>, <code>Inf</code>, and <code>NaN</code>. <p><code>NULL</code> is used to indicate the empty object. <code>NA</code> is used for absent (“Not Available”) data values. <code>Inf</code> denotes infinity and <code>NaN</code> is not-a-number in the <acronym>IEEE</acronym> floating point calculus (results of the operations respectively 1/0 and 0/0, for instance). <p>Logical constants are either <code>TRUE</code> or <code>FALSE</code>. <p>Numeric constants follow a similar syntax to that of the <strong>C</strong> language. They consist of an integer part consisting of zero or more digits, followed optionally by ‘<samp><span class="samp">.</span></samp>’ and a fractional part of zero or more digits optionally followed by an exponent part consisting of an ‘<samp><span class="samp">E</span></samp>’ or an ‘<samp><span class="samp">e</span></samp>’, an optional sign and a string of one or more digits. Either the fractional or the decimal part can be empty, but not both at once. <pre class="example"> <span class="roman">Valid numeric constants:</span> 1 10 0.1 .2 1e-7 1.2e+7 </pre> <p>Numeric constants can also be hexadecimal, starting with ‘<samp><span class="samp">0x</span></samp>’ or ‘<samp><span class="samp">0x</span></samp>’ followed by zero or more digits, ‘<samp><span class="samp">a-f</span></samp>’ or ‘<samp><span class="samp">A-F</span></samp>’. Hexadecimal floating point constants are supported using C99 syntax, e.g. ‘<samp><span class="samp">0x1.1p1</span></samp>’. <p>There is now a separate class of integer constants. They are created by using the qualifier <code>L</code> at the end of the number. For example, <code>123L</code> gives an integer value rather than a numeric value. The suffix <code>L</code> can be used to qualify any non-complex number with the intent of creating an integer. So it can be used with numbers given by hexadecimal or scientific notation. However, if the value is not a valid integer, a warning is emitted and the numeric value created. The following shows examples of valid integer constants, values which will generate a warning and give numeric constants and syntax errors. <pre class="example"> <span class="roman">Valid integer constants:</span> 1L, 0x10L, 1000000L, 1e6L <span class="roman">Valid numeric constants:</span> 1.1L, 1e-3L, 0x1.1p-2 <span class="roman">Syntax error:</span> 12iL 0x1.1 </pre> <p>A warning is emitted for decimal values that contain an unnecessary decimal point, e.g. <code>1.L</code>. It is an error to have a decimal point in a hexadecimal constant without the binary exponent. <p>Note also that a preceding sign (<code>+</code> or <code>-</code>) is treated as a unary operator, not as part of the constant. <p>Up-to-date information on the currently accepted formats can be found by <code>?NumericConstants</code>. <p>Complex constants have the form of a decimal numeric constant followed by ‘<samp><span class="samp">i</span></samp>’. Notice that only purely imaginary numbers are actual constants, other complex numbers are parsed a unary or binary operations on numeric and imaginary numbers. <pre class="example"> <span class="roman">Valid complex constants:</span> 2i 4.1i 1e-2i </pre> <p>String constants are delimited by a pair of single (‘<samp><span class="samp">'</span></samp>’) or double (‘<samp><span class="samp">"</span></samp>’) quotes and can contain all other printable characters. Quotes and other special characters within strings are specified using <em>escape sequences</em>: <dl> <dt><code>\'</code><dd>single quote <br><dt><code>\"</code><dd>double quote <br><dt><code>\n</code><dd>newline <br><dt><code>\r</code><dd>carriage return <br><dt><code>\t</code><dd>tab character <br><dt><code>\b</code><dd>backspace <br><dt><code>\a</code><dd>bell <br><dt><code>\f</code><dd>form feed <br><dt><code>\v</code><dd>vertical tab <br><dt><code>\\</code><dd>backslash itself <br><dt><code>\</code><var>nnn</var><dd>character with given octal code – sequences of one, two or three digits in the range <code>0 ... 7</code> are accepted. <br><dt><code>\x</code><var>nn</var><dd>character with given hex code – sequences of one or two hex digits (with entries <code>0 ... 9 A ... F a ... f</code>). <br><dt><code>\u</code><var>nnnn</var><code> \u{</code><var>nnnn</var><code>}</code><dd>(where multibyte locales are supported, otherwise an error). Unicode character with given hex code – sequences of up to four hex digits. The character needs to be valid in the current locale. <br><dt><code>\U</code><var>nnnnnnnn</var><code> \U{</code><var>nnnnnnnn</var><code>}</code><dd>(where multibyte locales are supported and not on Windows, otherwise an error). Unicode character with given hex code – sequences of up to eight hex digits. </dl> <p class="noindent">A single quote may also be embedded directly in a double-quote delimited string and vice versa. <p>As from R 2.8.0, a ‘nul’ (<code>\0</code>) is not allowed in a character string, so using <code>\0</code> in a string constant terminates the constant (usually with a warning): further characters up to the closing quote are scanned but ignored. <div class="node"> <a name="Identifiers"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Reserved-words">Reserved words</a>, Previous: <a rel="previous" accesskey="p" href="#Literal-constants">Literal constants</a>, Up: <a rel="up" accesskey="u" href="#Tokens">Tokens</a> </div> <h4 class="subsection">10.3.2 Identifiers</h4> <p><a name="index-identifier-285"></a>Identifiers consist of a sequence of letters, digits, the period (‘<samp><span class="samp">.</span></samp>’) and the underscore. They must not start with a digit nor underscore, nor with a period followed by a digit. <p>The definition of a letter depends on the current locale: the precise set of characters allowed is given by the C expression <code>(isalnum(c) || c == ‘.’ || c == ‘_’)</code> and will include accented letters in many Western European locales. <p>Notice that identifiers starting with a period are not by default listed by the <code>ls</code> function and that ‘<samp><span class="samp">...</span></samp>’ and ‘<samp><span class="samp">..1</span></samp>’, ‘<samp><span class="samp">..2</span></samp>’, etc. are special. <p>Notice also that objects can have names that are not identifiers. These are generally accessed via <code>get</code> and <code>assign</code>, although they can also be represented by text strings in some limited circumstances when there is no ambiguity (e.g. <code>"x" <- 1</code>). As <code>get</code> and <code>assign</code> are not restricted to names that are identifiers they do not recognise subscripting operators or replacement functions. The following pairs are <em>not</em> equivalent <a name="index-get-286"></a><a name="index-assign-287"></a> <blockquote> <p><table summary=""><tr align="left"><td valign="top"><code>x$a<-1</code> </td><td valign="top"><code>assign("x$a",1)</code> <br></td></tr><tr align="left"><td valign="top"><code>x[[1]]</code> </td><td valign="top"><code>get("x[[1]]")</code> <br></td></tr><tr align="left"><td valign="top"><code>names(x)<-nm</code> </td><td valign="top"><code>assign("names(x)",nm)</code> <br></td></tr></table> </blockquote> <div class="node"> <a name="Reserved-words"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Special-operators">Special operators</a>, Previous: <a rel="previous" accesskey="p" href="#Identifiers">Identifiers</a>, Up: <a rel="up" accesskey="u" href="#Tokens">Tokens</a> </div> <h4 class="subsection">10.3.3 Reserved words</h4> <p>The following identifiers have a special meaning and cannot be used for object names <pre class="example"> if else repeat while function for in next break TRUE FALSE NULL Inf NaN NA NA_integer_ NA_real_ NA_complex_ NA_character_ ... ..1 ..2 <span class="roman">etc.</span> </pre> <div class="node"> <a name="Special-operators"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Separators">Separators</a>, Previous: <a rel="previous" accesskey="p" href="#Reserved-words">Reserved words</a>, Up: <a rel="up" accesskey="u" href="#Tokens">Tokens</a> </div> <h4 class="subsection">10.3.4 Special operators</h4> <p>R allows user-defined infix operators. These have the form of a string of characters delimited by the ‘<samp><span class="samp">%</span></samp>’ character. The string can contain any printable character except ‘<samp><span class="samp">%</span></samp>’. The escape sequences for strings do not apply here. <p>Note that the following operators are predefined <pre class="example"> %% %*% %/% %in% %o% %x% </pre> <!-- @node Special symbols, Separators, Special operators, Tokens --> <!-- @subsection Special symbols --> <!-- @c (I can't for the life of me remember what I intended here... -pd) --> <!-- .....possibly "..." and friends which are currently "reserved --> <!-- words" --> <!-- FIXME: get this clarified --> <div class="node"> <a name="Separators"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Operator-tokens">Operator tokens</a>, Previous: <a rel="previous" accesskey="p" href="#Special-operators">Special operators</a>, Up: <a rel="up" accesskey="u" href="#Tokens">Tokens</a> </div> <h4 class="subsection">10.3.5 Separators</h4> <p>Although not strictly tokens, stretches of whitespace characters (spaces, tabs and formfeeds, on Windows and UTF-8 locales other Unicode whitespace characters<a rel="footnote" href="#fn-4" name="fnd-4"><sup>4</sup></a>) serve to delimit tokens in case of ambiguity, (compare <code>x<-5</code> and <code>x < -5</code>). <p>Newlines have a function which is a combination of token separator and expression terminator. If an expression can terminate at the end of the line the parser will assume it does so, otherwise the newline is treated as whitespace. Semicolons (‘<samp><span class="samp">;</span></samp>’) may be used to separate elementary <a name="index-expression-288"></a>expressions on the same line. <p>Special rules apply to the <code>else</code> keyword: inside a compound expression, a newline before <code>else</code> is discarded, whereas at the outermost level, the newline terminates the <code>if</code> construction and a subsequent <code>else</code> causes a syntax error. This somewhat anomalous behaviour occurs because R should be usable in interactive mode and then it must decide whether the input expression is complete, incomplete, or invalid as soon as the user presses <RET>. <p>The comma (‘<samp><span class="samp">,</span></samp>’) is used to separate function arguments and multiple indices. <div class="node"> <a name="Operator-tokens"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Grouping">Grouping</a>, Previous: <a rel="previous" accesskey="p" href="#Separators">Separators</a>, Up: <a rel="up" accesskey="u" href="#Tokens">Tokens</a> </div> <h4 class="subsection">10.3.6 Operator tokens</h4> <p>R uses the following operator tokens <blockquote> <p><table summary=""><tr align="left"><td valign="top" width="30%"><code>+ - * / %% ^</code> </td><td valign="top" width="60%">arithmetic <br></td></tr><tr align="left"><td valign="top" width="30%"><code>> >= < <= == !=</code> </td><td valign="top" width="60%">relational <br></td></tr><tr align="left"><td valign="top" width="30%"><code>! & |</code> </td><td valign="top" width="60%">logical <br></td></tr><tr align="left"><td valign="top" width="30%"><code>~</code> </td><td valign="top" width="60%">model formulae <br></td></tr><tr align="left"><td valign="top" width="30%"><code>-> <-</code> </td><td valign="top" width="60%">assignment <br></td></tr><tr align="left"><td valign="top" width="30%"><code>$</code> </td><td valign="top" width="60%">list indexing <br></td></tr><tr align="left"><td valign="top" width="30%"><code>:</code> </td><td valign="top" width="60%">sequence <br></td></tr></table> </blockquote> <p class="noindent">(Several of the operators have different meaning inside model formulas) <div class="node"> <a name="Grouping"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Indexing-tokens">Indexing tokens</a>, Previous: <a rel="previous" accesskey="p" href="#Operator-tokens">Operator tokens</a>, Up: <a rel="up" accesskey="u" href="#Tokens">Tokens</a> </div> <h4 class="subsection">10.3.7 Grouping</h4> <p>Ordinary parentheses—‘<samp><span class="samp">(</span></samp>’ and ‘<samp><span class="samp">)</span></samp>’—are used for explicit grouping within expressions and to delimit the argument lists for function definitions and function calls. <p>Braces—‘<samp><span class="samp">{</span></samp>’ and ‘<samp><span class="samp">}</span></samp>’—delimit blocks of expressions in function definitions, conditional expressions, and iterative constructs. <div class="node"> <a name="Indexing-tokens"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Grouping">Grouping</a>, Up: <a rel="up" accesskey="u" href="#Tokens">Tokens</a> </div> <h4 class="subsection">10.3.8 Indexing tokens</h4> <p>Indexing of arrays and vectors performed using the single and double brackets, ‘<samp><span class="samp">[]</span></samp>’ and ‘<samp><span class="samp">[[]]</span></samp>’. Also, indexing tagged lists may be done using the ‘<samp><span class="samp">$</span></samp>’ operator. <!-- end of @section Tokens - --> <div class="node"> <a name="Expressions"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Directives">Directives</a>, Previous: <a rel="previous" accesskey="p" href="#Tokens">Tokens</a>, Up: <a rel="up" accesskey="u" href="#Parser">Parser</a> </div> <h3 class="section">10.4 Expressions</h3> <p>An R program consists of a sequence of R expressions. An expression can be a simple expression consisting of only a constant or an identifier, or it can be a compound expression constructed from other parts (which may themselves be expressions). <p>The following sections detail the various syntactical constructs that are available. <ul class="menu"> <li><a accesskey="1" href="#Function-calls-_0028expressions_0029">Function calls (expressions)</a> <li><a accesskey="2" href="#Infix-and-prefix-operators">Infix and prefix operators</a> <li><a accesskey="3" href="#Index-constructions">Index constructions</a> <li><a accesskey="4" href="#Compound-expressions">Compound expressions</a> <li><a accesskey="5" href="#Flow-control-elements">Flow control elements</a> <li><a accesskey="6" href="#Function-definitions">Function definitions</a> </ul> <!-- need "(expressions)" or something to differentiate from node --> <!-- "Function calls" (way) above : --> <div class="node"> <a name="Function-calls-(expressions)"></a> <a name="Function-calls-_0028expressions_0029"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Infix-and-prefix-operators">Infix and prefix operators</a>, Previous: <a rel="previous" accesskey="p" href="#Expressions">Expressions</a>, Up: <a rel="up" accesskey="u" href="#Expressions">Expressions</a> </div> <h4 class="subsection">10.4.1 Function calls</h4> <p><a name="index-function-289"></a>A function call takes the form of a function reference followed by a comma-separated list of arguments within a set of parentheses. <pre class="example"> <var>function_reference</var> ( <var>arg1</var>, <var>arg2</var>, ...... , <var>argn</var> ) </pre> <p>The function reference can be either <ul> <li>an identifier (the name of the function) <li>a text string (ditto, but handy if the function has a name which is not a valid identifier) <li>an expression (which should evaluate to a function object) </ul> <p>Each argument can be tagged (<var>tag</var><code>=</code><var>expr</var>), or just be a simple expression. It can also be empty or it can be one of the special tokens ‘<samp><span class="samp">...</span></samp>’, ‘<samp><span class="samp">..2</span></samp>’, etc. <p>A tag can be an identifier or a text string. <p>Examples: <pre class="example"> f(x) g(tag = value, , 5) "odd name"("strange tag" = 5, y) (function(x) x^2)(5) </pre> <div class="node"> <a name="Infix-and-prefix-operators"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Index-constructions">Index constructions</a>, Previous: <a rel="previous" accesskey="p" href="#Function-calls-_0028expressions_0029">Function calls (expressions)</a>, Up: <a rel="up" accesskey="u" href="#Expressions">Expressions</a> </div> <h4 class="subsection">10.4.2 Infix and prefix operators</h4> <p>The order of precedence (highest first) of the operators are <pre class="example"> :: $ @ ^ - + <span class="roman">(unary)</span> : %<var>xyz</var>% * / + - <span class="roman">(binary)</span> > >= < <= == != ! & && | || ~ <span class="roman">(unary and binary)</span> -> ->> = <span class="roman">(as assignment)</span> <- <<- </pre> <p>The exponentiation operator ‘<samp><span class="samp">^</span></samp>’ and the <a name="index-assignment-290"></a>left assignment operators ‘<samp><span class="samp"><- - = <<-</span></samp>’ group right to left, all other operators group left to right. That is, <code>2 ^ 2 ^ 3</code> is 2 ^ 8, not 4 ^ 3, whereas <code>1 - 1 - 1</code> is -1, not 1. <p>Notice that the operators <code>%%</code> and <code>%/%</code> for integer remainder and divide have higher precedence than multiply and divide. <p>Although it is not strictly an operator, it also needs mentioning that the ‘<samp><span class="samp">=</span></samp>’ sign is used for tagging arguments in function calls and for assigning default values in function definitions. <p>The ‘<samp><span class="samp">$</span></samp>’ sign is in some sense an operator, but does not allow arbitrary right hand sides and is discussed under <a href="#Index-constructions">Index constructions</a>. It has higher precedence than any of the other operators. <p>The parsed form of a unary or binary operation is completely equivalent to a function call with the operator as the function name and the operands as the function arguments. <p>Parentheses are recorded as equivalent to a unary operator, with name <code>"("</code>, even in cases where the parentheses could be inferred from operator precedence (e.g., <code>a * (b + c)</code>). <!-- FIXME: Will this get changed? --> <p>Notice that the <a name="index-assignment-291"></a>assignment symbols are operators just like the arithmetic, relational, and logical ones. Any expressions is allowed also on the target side of an assignment, as far as the parser is concerned (<code>2 + 2 <- 5</code> is a valid expression as far as the parser is concerned. The evaluator will object, though). Similar comments apply to the model formula operator. <div class="node"> <a name="Index-constructions"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Compound-expressions">Compound expressions</a>, Previous: <a rel="previous" accesskey="p" href="#Infix-and-prefix-operators">Infix and prefix operators</a>, Up: <a rel="up" accesskey="u" href="#Expressions">Expressions</a> </div> <h4 class="subsection">10.4.3 Index constructions</h4> <p>R has three indexing constructs, two of which are syntactically similar although with somewhat different semantics: <pre class="example"> <var>object</var> [ <var>arg1</var>, ...... , <var>argn</var> ] <var>object</var> [[ <var>arg1</var>, ...... , <var>argn</var> ]] </pre> <p><a name="index-g_t_005b-292"></a><a name="index-g_t_005b_005b-293"></a> The <var>object</var> can formally be any valid expression, but it is understood to denote or evaluate to a subsettable object. The arguments generally evaluate to numerical or character indices, but other kinds of arguments are possible (notably <code>drop = FALSE</code>). <p>Internally, these index constructs are stored as function calls with function name <code>"["</code> respectively <code>"[["</code>. <p>The third index construction is <pre class="example"> <var>object</var> $ <var>tag</var> </pre> <p><a name="index-g_t_0024-294"></a> Here, <var>object</var> is as above, whereas <var>tag</var> is an identifier or a text string. Internally, it is stored as a function call with name <code>"$"</code> <!-- @node Assignments, Model formulae, Index constructions, Expressions --> <!-- @subsection Assignments --> <!-- @node Model formulae, Flow control elements, Assignments, Expressions --> <!-- @subsection Model formulae --> <div class="node"> <a name="Compound-expressions"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Flow-control-elements">Flow control elements</a>, Previous: <a rel="previous" accesskey="p" href="#Index-constructions">Index constructions</a>, Up: <a rel="up" accesskey="u" href="#Expressions">Expressions</a> </div> <h4 class="subsection">10.4.4 Compound expressions</h4> <p>A compound expression is of the form <pre class="example"> { <var>expr1</var> ; <var>expr2</var> ; ...... ; <var>exprn</var> } </pre> <p>The semicolons may be replaced by newlines. Internally, this is stored as a function call with <code>"{"</code> as the function name and the expressions as arguments. <div class="node"> <a name="Flow-control-elements"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Function-definitions">Function definitions</a>, Previous: <a rel="previous" accesskey="p" href="#Compound-expressions">Compound expressions</a>, Up: <a rel="up" accesskey="u" href="#Expressions">Expressions</a> </div> <h4 class="subsection">10.4.5 Flow control elements</h4> <p>R contains the following control structures as special syntactic constructs <pre class="example"> if ( <var>cond</var> ) <var>expr</var> if ( <var>cond</var> ) <var>expr1</var> else <var>expr2</var> while ( <var>cond</var> ) <var>expr</var> repeat <var>expr</var> for ( <var>var</var> in <var>list</var> ) <var>expr</var> </pre> <p>The expressions in these constructs will typically be compound expressions. <p>Within the loop constructs (<code>while</code>, <code>repeat</code>, <code>for</code>), one may use <code>break</code> (to terminate the loop) and <code>next</code> (to skip to the next iteration). <p>Internally, the constructs are stored as function calls: <pre class="example"> "if"(<var>cond</var>, <var>expr</var>) "if"(<var>cond</var>, <var>expr1</var>, <var>expr2</var>) "while"(<var>cond</var>, <var>expr</var>) "repeat"(<var>expr</var>) "for"(<var>var</var>, <var>list</var>, <var>expr</var>) "break"() "next"() </pre> <div class="node"> <a name="Function-definitions"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Flow-control-elements">Flow control elements</a>, Up: <a rel="up" accesskey="u" href="#Expressions">Expressions</a> </div> <h4 class="subsection">10.4.6 Function definitions</h4> <p>A <a name="index-function-295"></a>function definition is of the form <pre class="example"> function ( <var>arglist</var> ) <var>body</var> </pre> <p>The function body is an expression, often a compound expression. The <var>arglist</var> is a comma-separated list of items each of which can be an identifier, or of the form ‘<samp><var>identifier</var><span class="samp"> = </span><var>default</var></samp>’, or the special token ‘<samp><span class="samp">...</span></samp>’. The <var>default</var> can be any valid expression. <p>Notice that function arguments unlike list tags, etc., cannot have “strange names” given as text strings. <!-- FIXME: is there a good reason for this? --> <p>Internally, a function definition is stored as a function call with function name <code>function</code> and two arguments, the <var>arglist</var> and the <var>body</var>. The <var>arglist</var> is stored as a tagged pairlist where the tags are the argument names and the values are the default expressions. <div class="node"> <a name="Directives"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Expressions">Expressions</a>, Up: <a rel="up" accesskey="u" href="#Parser">Parser</a> </div> <h3 class="section">10.5 Directives</h3> <p><a name="index-g_t_0023line-296"></a> The parser currently only supports one directive, <code>#line</code>. This is similar to the C-preprocessor directive of the same name. The syntax is <pre class="example"> <var>#line</var> <var>nn</var> [ <code>"filename"</code> ] </pre> <p>where <var>nn</var> is an integer line number, and the optional <var>filename</var> (in required double quotes) names the source file. <p>Unlike the C directive, <code>#line</code> must appear as the first five characters on a line. As in C, <var>nn</var> and <code>"filename"</code> entries may be separated from it by whitespace. And unlike C, any following text on the line will be treated as a comment and ignored. <p>This directive tells the parser that the following line should be assumed to be line <var>nn</var> of file <var>filename</var>. (If the filename is not given, it is assumed to be the same as for the previous directive.) This is not typically used by users, but may be used by preprocessors so that diagnostic messages refer to the original file. <!-- We can probably lose this given the brevity of the section --> <!-- @node Summary , , Syntactic elements, Parser --> <!-- @section Summary of language --> <div class="node"> <a name="Function-and-Variable-Index"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#Concept-Index">Concept Index</a>, Previous: <a rel="previous" accesskey="p" href="#Parser">Parser</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="unnumbered">Function and Variable Index</h2> <ul class="index-vr" compact> <li><a href="#index-g_t_0040code_007b_0023_007d-284"><code>#</code></a>: <a href="#Comments">Comments</a></li> <li><a href="#index-g_t_0024-294"><code>$</code></a>: <a href="#Index-constructions">Index constructions</a></li> <li><a href="#index-g_t_0024-114"><code>$</code></a>: <a href="#Indexing">Indexing</a></li> <li><a href="#index-g_t_002eC-261"><code>.C</code></a>: <a href="#Foreign-language-interfaces">Foreign language interfaces</a></li> <li><a href="#index-g_t_002eCall-263"><code>.Call</code></a>: <a href="#Foreign-language-interfaces">Foreign language interfaces</a></li> <li><a href="#index-g_t_002eExternal-264"><code>.External</code></a>: <a href="#Foreign-language-interfaces">Foreign language interfaces</a></li> <li><a href="#index-g_t_002eFortran-262"><code>.Fortran</code></a>: <a href="#Foreign-language-interfaces">Foreign language interfaces</a></li> <li><a href="#index-g_t_002eInternal-265"><code>.Internal</code></a>: <a href="#g_t_002eInternal-and-_002ePrimitive">.Internal and .Primitive</a></li> <li><a href="#index-g_t_002ePrimitive-266"><code>.Primitive</code></a>: <a href="#g_t_002eInternal-and-_002ePrimitive">.Internal and .Primitive</a></li> <li><a href="#index-g_t_005b-292"><code>[</code></a>: <a href="#Index-constructions">Index constructions</a></li> <li><a href="#index-g_t_005b-112"><code>[</code></a>: <a href="#Indexing">Indexing</a></li> <li><a href="#index-g_t_005b_005b-293"><code>[[</code></a>: <a href="#Index-constructions">Index constructions</a></li> <li><a href="#index-g_t_005b_005b-113"><code>[[</code></a>: <a href="#Indexing">Indexing</a></li> <li><a href="#index-as_002ecall-26"><code>as.call</code></a>: <a href="#Language-objects">Language objects</a></li> <li><a href="#index-as_002echaracter-34"><code>as.character</code></a>: <a href="#Symbol-objects">Symbol objects</a></li> <li><a href="#index-as_002efunction-51"><code>as.function</code></a>: <a href="#Function-objects">Function objects</a></li> <li><a href="#index-as_002elist-25"><code>as.list</code></a>: <a href="#Language-objects">Language objects</a></li> <li><a href="#index-as_002ename-35"><code>as.name</code></a>: <a href="#Symbol-objects">Symbol objects</a></li> <li><a href="#index-assign-287"><code>assign</code></a>: <a href="#Identifiers">Identifiers</a></li> <li><a href="#index-attr-74"><code>attr</code></a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-attr_003c_002d-75"><code>attr<-</code></a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-attributes-72"><code>attributes</code></a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-attributes_003c_002d-73"><code>attributes<-</code></a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-baseenv-66"><code>baseenv</code></a>: <a href="#Environment-objects">Environment objects</a></li> <li><a href="#index-basename-257"><code>basename</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-body-227"><code>body</code></a>: <a href="#Manipulation-of-functions">Manipulation of functions</a></li> <li><a href="#index-body-48"><code>body</code></a>: <a href="#Function-objects">Function objects</a></li> <li><a href="#index-body_003c_002d-231"><code>body<-</code></a>: <a href="#Manipulation-of-functions">Manipulation of functions</a></li> <li><a href="#index-break-98"><code>break</code></a>: <a href="#Looping">Looping</a></li> <li><a href="#index-browser-274"><code>browser</code></a>: <a href="#browser">browser</a></li> <li><a href="#index-debug-275"><code>debug</code></a>: <a href="#debug_002fundebug">debug/undebug</a></li> <li><a href="#index-dirname-258"><code>dirname</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-do_002ecall-225"><code>do.call</code></a>: <a href="#Manipulation-of-function-calls">Manipulation of function calls</a></li> <li><a href="#index-emptyenv-65"><code>emptyenv</code></a>: <a href="#Environment-objects">Environment objects</a></li> <li><a href="#index-environment-229"><code>environment</code></a>: <a href="#Manipulation-of-functions">Manipulation of functions</a></li> <li><a href="#index-environment-49"><code>environment</code></a>: <a href="#Function-objects">Function objects</a></li> <li><a href="#index-environment_003c_002d-233"><code>environment<-</code></a>: <a href="#Manipulation-of-functions">Manipulation of functions</a></li> <li><a href="#index-eval-217"><code>eval</code></a>: <a href="#More-on-evaluation">More on evaluation</a></li> <li><a href="#index-file_002eaccess-246"><code>file.access</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-file_002eappend-247"><code>file.append</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-file_002echoose-248"><code>file.choose</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-file_002ecopy-249"><code>file.copy</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-file_002ecreate-250"><code>file.create</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-file_002eexists-251"><code>file.exists</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-file_002einfo-252"><code>file.info</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-file_002epath-259"><code>file.path</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-file_002eremove-253"><code>file.remove</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-file_002erename-254"><code>file.rename</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-file_002eshow-255"><code>file.show</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-for-102"><code>for</code></a>: <a href="#for">for</a></li> <li><a href="#index-formals-228"><code>formals</code></a>: <a href="#Manipulation-of-functions">Manipulation of functions</a></li> <li><a href="#index-formals-47"><code>formals</code></a>: <a href="#Function-objects">Function objects</a></li> <li><a href="#index-formals_003c_002d-232"><code>formals<-</code></a>: <a href="#Manipulation-of-functions">Manipulation of functions</a></li> <li><a href="#index-get-286"><code>get</code></a>: <a href="#Identifiers">Identifiers</a></li> <li><a href="#index-is_002ena-109"><code>is.na</code></a>: <a href="#NA-handling">NA handling</a></li> <li><a href="#index-is_002enan-110"><code>is.nan</code></a>: <a href="#NA-handling">NA handling</a></li> <li><a href="#index-match_002earg-155"><code>match.arg</code></a>: <a href="#Argument-matching">Argument matching</a></li> <li><a href="#index-match_002ecall-223"><code>match.call</code></a>: <a href="#Manipulation-of-function-calls">Manipulation of function calls</a></li> <li><a href="#index-match_002ecall-156"><code>match.call</code></a>: <a href="#Argument-matching">Argument matching</a></li> <li><a href="#index-match_002efun-157"><code>match.fun</code></a>: <a href="#Argument-matching">Argument matching</a></li> <li><a href="#index-missing-105"><code>missing</code></a>: <a href="#NA-handling">NA handling</a></li> <li><a href="#index-mode-7"><code>mode</code></a>: <a href="#Objects">Objects</a></li> <li><a href="#index-NA-118"><code>NA</code></a>: <a href="#Indexing-by-vectors">Indexing by vectors</a></li> <li><a href="#index-NA-106"><code>NA</code></a>: <a href="#NA-handling">NA handling</a></li> <li><a href="#index-names-78"><code>names</code></a>: <a href="#Names">Names</a></li> <li><a href="#index-names_003c_002d-79"><code>names<-</code></a>: <a href="#Names">Names</a></li> <li><a href="#index-NaN-107"><code>NaN</code></a>: <a href="#NA-handling">NA handling</a></li> <li><a href="#index-new_002eenv-67"><code>new.env</code></a>: <a href="#Environment-objects">Environment objects</a></li> <li><a href="#index-next-99"><code>next</code></a>: <a href="#Looping">Looping</a></li> <li><a href="#index-NextMethod-202"><code>NextMethod</code></a>: <a href="#NextMethod">NextMethod</a></li> <li><a href="#index-NULL-52"><code>NULL</code></a>: <a href="#NULL-object">NULL object</a></li> <li><a href="#index-on_002eexit-270"><code>on.exit</code></a>: <a href="#on_002eexit">on.exit</a></li> <li><a href="#index-pairlist-68"><code>pairlist</code></a>: <a href="#Pairlist-objects">Pairlist objects</a></li> <li><a href="#index-path_002eexpand-260"><code>path.expand</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-proc_002etime-237"><code>proc.time</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-quote-24"><code>quote</code></a>: <a href="#Language-objects">Language objects</a></li> <li><a href="#index-repeat-100"><code>repeat</code></a>: <a href="#repeat">repeat</a></li> <li><a href="#index-stop-267"><code>stop</code></a>: <a href="#stop">stop</a></li> <li><a href="#index-storage_002emode-9"><code>storage.mode</code></a>: <a href="#Objects">Objects</a></li> <li><a href="#index-substitute-210"><code>substitute</code></a>: <a href="#Substitutions">Substitutions</a></li> <li><a href="#index-switch-103"><code>switch</code></a>: <a href="#switch">switch</a></li> <li><a href="#index-Sys_002egetenv-239"><code>Sys.getenv</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-Sys_002egetlocale-241"><code>Sys.getlocale</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-Sys_002elocaleconv-243"><code>Sys.localeconv</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-Sys_002eputenv-240"><code>Sys.putenv</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-Sys_002eputlocale-242"><code>Sys.putlocale</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-Sys_002etime-244"><code>Sys.time</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-Sys_002etimezone-245"><code>Sys.timezone</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-system-235"><code>system</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-system_002etime-236"><code>system.time</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-trace-277"><code>trace</code></a>: <a href="#trace_002funtrace">trace/untrace</a></li> <li><a href="#index-traceback-279"><code>traceback</code></a>: <a href="#traceback">traceback</a></li> <li><a href="#index-typeof-4"><code>typeof</code></a>: <a href="#Objects">Objects</a></li> <li><a href="#index-undebug-276"><code>undebug</code></a>: <a href="#debug_002fundebug">debug/undebug</a></li> <li><a href="#index-unlink-256"><code>unlink</code></a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-untrace-278"><code>untrace</code></a>: <a href="#trace_002funtrace">trace/untrace</a></li> <li><a href="#index-UseMethod-196"><code>UseMethod</code></a>: <a href="#UseMethod">UseMethod</a></li> <li><a href="#index-warning-268"><code>warning</code></a>: <a href="#warning">warning</a></li> <li><a href="#index-warnings-269"><code>warnings</code></a>: <a href="#warning">warning</a></li> <li><a href="#index-while-101"><code>while</code></a>: <a href="#while">while</a></li> </ul><div class="node"> <a name="Concept-Index"></a> <p><hr> Next: <a rel="next" accesskey="n" href="#References">References</a>, Previous: <a rel="previous" accesskey="p" href="#Function-and-Variable-Index">Function and Variable Index</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="unnumbered">Concept Index</h2> <ul class="index-cp" compact> <li><a href="#index-g_t_0023line-296">#line</a>: <a href="#Directives">Directives</a></li> <li><a href="#index-g_t_002eInternal-55">.Internal</a>: <a href="#Builtin-objects-and-special-forms">Builtin objects and special forms</a></li> <li><a href="#index-g_t_002ePrimitive-54">.Primitive</a>: <a href="#Builtin-objects-and-special-forms">Builtin objects and special forms</a></li> <li><a href="#index-argument-143">argument</a>: <a href="#Syntax-and-examples">Syntax and examples</a></li> <li><a href="#index-argument-43">argument</a>: <a href="#Function-objects">Function objects</a></li> <li><a href="#index-argument_002c-default-values-146">argument, default values</a>: <a href="#Arguments">Arguments</a></li> <li><a href="#index-assignment-290">assignment</a>: <a href="#Infix-and-prefix-operators">Infix and prefix operators</a></li> <li><a href="#index-assignment-222">assignment</a>: <a href="#Manipulation-of-function-calls">Manipulation of function calls</a></li> <li><a href="#index-assignment-219">assignment</a>: <a href="#More-on-evaluation">More on evaluation</a></li> <li><a href="#index-assignment-200">assignment</a>: <a href="#UseMethod">UseMethod</a></li> <li><a href="#index-assignment-177">assignment</a>: <a href="#Scope">Scope</a></li> <li><a href="#index-assignment-161">assignment</a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-assignment-126">assignment</a>: <a href="#Global-environment">Global environment</a></li> <li><a href="#index-assignment-121">assignment</a>: <a href="#Subset-assignment">Subset assignment</a></li> <li><a href="#index-assignment-96">assignment</a>: <a href="#Operators">Operators</a></li> <li><a href="#index-assignment-94">assignment</a>: <a href="#Function-calls">Function calls</a></li> <li><a href="#index-assignment-46">assignment</a>: <a href="#Function-objects">Function objects</a></li> <li><a href="#index-atomic-18">atomic</a>: <a href="#Vector-objects">Vector objects</a></li> <li><a href="#index-attributes-70">attributes</a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-binding-173">binding</a>: <a href="#Scope">Scope</a></li> <li><a href="#index-call-20">call</a>: <a href="#Language-objects">Language objects</a></li> <li><a href="#index-call-stack-136">call stack</a>: <a href="#Stacks">Stacks</a></li> <li><a href="#index-coercion-111">coercion</a>: <a href="#NA-handling">NA handling</a></li> <li><a href="#index-coercion-82">coercion</a>: <a href="#Classes">Classes</a></li> <li><a href="#index-coercion-69">coercion</a>: <a href="#Any_002dtype">Any-type</a></li> <li><a href="#index-coercion-33">coercion</a>: <a href="#Symbol-objects">Symbol objects</a></li> <li><a href="#index-coercion-12">coercion</a>: <a href="#Objects">Objects</a></li> <li><a href="#index-comments-283">comments</a>: <a href="#Comments">Comments</a></li> <li><a href="#index-complex-assignment-122">complex assignment</a>: <a href="#Subset-assignment">Subset assignment</a></li> <li><a href="#index-environment-297">environment</a>: <a href="#Footnotes">Footnotes</a></li> <li><a href="#index-environment-271">environment</a>: <a href="#Debugging">Debugging</a></li> <li><a href="#index-environment-238">environment</a>: <a href="#Operating-system-access">Operating system access</a></li> <li><a href="#index-environment-230">environment</a>: <a href="#Manipulation-of-functions">Manipulation of functions</a></li> <li><a href="#index-environment-216">environment</a>: <a href="#More-on-evaluation">More on evaluation</a></li> <li><a href="#index-environment-198">environment</a>: <a href="#UseMethod">UseMethod</a></li> <li><a href="#index-environment-178">environment</a>: <a href="#Scope">Scope</a></li> <li><a href="#index-environment-162">environment</a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-environment-152">environment</a>: <a href="#Evaluation-environment">Evaluation environment</a></li> <li><a href="#index-environment-138">environment</a>: <a href="#Search-path">Search path</a></li> <li><a href="#index-environment-135">environment</a>: <a href="#Stacks">Stacks</a></li> <li><a href="#index-environment-129">environment</a>: <a href="#Lexical-environment">Lexical environment</a></li> <li><a href="#index-environment-125">environment</a>: <a href="#Global-environment">Global environment</a></li> <li><a href="#index-environment-64">environment</a>: <a href="#Environment-objects">Environment objects</a></li> <li><a href="#index-environment-58">environment</a>: <a href="#Promise-objects">Promise objects</a></li> <li><a href="#index-environment-42">environment</a>: <a href="#Function-objects">Function objects</a></li> <li><a href="#index-environment_002c-evaluation-163">environment, evaluation</a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-environment_002c-evaluation-130">environment, evaluation</a>: <a href="#Lexical-environment">Lexical environment</a></li> <li><a href="#index-evaluation-221">evaluation</a>: <a href="#Manipulation-of-function-calls">Manipulation of function calls</a></li> <li><a href="#index-evaluation-215">evaluation</a>: <a href="#More-on-evaluation">More on evaluation</a></li> <li><a href="#index-evaluation-197">evaluation</a>: <a href="#UseMethod">UseMethod</a></li> <li><a href="#index-evaluation-191">evaluation</a>: <a href="#Inheritance">Inheritance</a></li> <li><a href="#index-evaluation-180">evaluation</a>: <a href="#Scope">Scope</a></li> <li><a href="#index-evaluation-167">evaluation</a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-evaluation-151">evaluation</a>: <a href="#Evaluation-environment">Evaluation environment</a></li> <li><a href="#index-evaluation-137">evaluation</a>: <a href="#Stacks">Stacks</a></li> <li><a href="#index-evaluation_002c-argument-158">evaluation, argument</a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-evaluation_002c-expression-147">evaluation, expression</a>: <a href="#Arguments">Arguments</a></li> <li><a href="#index-evaluation_002c-expression-61">evaluation, expression</a>: <a href="#Promise-objects">Promise objects</a></li> <li><a href="#index-evaluation_002c-expression-39">evaluation, expression</a>: <a href="#Expression-objects">Expression objects</a></li> <li><a href="#index-evaluation_002c-lazy-211">evaluation, lazy</a>: <a href="#Substitutions">Substitutions</a></li> <li><a href="#index-evaluation_002c-lazy-6">evaluation, lazy</a>: <a href="#Objects">Objects</a></li> <li><a href="#index-evaluation_002c-statement-97">evaluation, statement</a>: <a href="#Control-structures">Control structures</a></li> <li><a href="#index-evaluation_002c-symbol-171">evaluation, symbol</a>: <a href="#Scope">Scope</a></li> <li><a href="#index-evaluation_002c-symbol-88">evaluation, symbol</a>: <a href="#Symbol-lookup">Symbol lookup</a></li> <li><a href="#index-evaluation_002c-symbol-77">evaluation, symbol</a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-expression-288">expression</a>: <a href="#Separators">Separators</a></li> <li><a href="#index-expression-21">expression</a>: <a href="#Language-objects">Language objects</a></li> <li><a href="#index-expression-1">expression</a>: <a href="#Introduction">Introduction</a></li> <li><a href="#index-expression-object-38">expression object</a>: <a href="#Expression-objects">Expression objects</a></li> <li><a href="#index-frame-128">frame</a>: <a href="#Lexical-environment">Lexical environment</a></li> <li><a href="#index-function-295">function</a>: <a href="#Function-definitions">Function definitions</a></li> <li><a href="#index-function-289">function</a>: <a href="#Function-calls-_0028expressions_0029">Function calls (expressions)</a></li> <li><a href="#index-function-282">function</a>: <a href="#Internal-representation">Internal representation</a></li> <li><a href="#index-function-226">function</a>: <a href="#Manipulation-of-functions">Manipulation of functions</a></li> <li><a href="#index-function-220">function</a>: <a href="#Manipulation-of-function-calls">Manipulation of function calls</a></li> <li><a href="#index-function-188">function</a>: <a href="#Definition">Definition</a></li> <li><a href="#index-function-184">function</a>: <a href="#Object_002doriented-programming">Object-oriented programming</a></li> <li><a href="#index-function-175">function</a>: <a href="#Scope">Scope</a></li> <li><a href="#index-function-159">function</a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-function-153">function</a>: <a href="#Argument-matching">Argument matching</a></li> <li><a href="#index-function-150">function</a>: <a href="#Evaluation-environment">Evaluation environment</a></li> <li><a href="#index-function-149">function</a>: <a href="#Arguments">Arguments</a></li> <li><a href="#index-function-142">function</a>: <a href="#Syntax-and-examples">Syntax and examples</a></li> <li><a href="#index-function-141">function</a>: <a href="#Writing-functions">Writing functions</a></li> <li><a href="#index-function-133">function</a>: <a href="#Stacks">Stacks</a></li> <li><a href="#index-function-127">function</a>: <a href="#Lexical-environment">Lexical environment</a></li> <li><a href="#index-function-91">function</a>: <a href="#Function-calls">Function calls</a></li> <li><a href="#index-function-62">function</a>: <a href="#Dot_002ddot_002ddot">Dot-dot-dot</a></li> <li><a href="#index-function-59">function</a>: <a href="#Promise-objects">Promise objects</a></li> <li><a href="#index-function-53">function</a>: <a href="#Builtin-objects-and-special-forms">Builtin objects and special forms</a></li> <li><a href="#index-function-41">function</a>: <a href="#Function-objects">Function objects</a></li> <li><a href="#index-function-argument-63">function argument</a>: <a href="#Dot_002ddot_002ddot">Dot-dot-dot</a></li> <li><a href="#index-function-argument-60">function argument</a>: <a href="#Promise-objects">Promise objects</a></li> <li><a href="#index-function-arguments-92">function arguments</a>: <a href="#Function-calls">Function calls</a></li> <li><a href="#index-function-invocation-90">function invocation</a>: <a href="#Function-calls">Function calls</a></li> <li><a href="#index-function_002c-accessor-76">function, accessor</a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-function_002c-anonymous-145">function, anonymous</a>: <a href="#Syntax-and-examples">Syntax and examples</a></li> <li><a href="#index-function_002c-assignment-93">function, assignment</a>: <a href="#Function-calls">Function calls</a></li> <li><a href="#index-function_002c-generic-205">function, generic</a>: <a href="#Writing-methods">Writing methods</a></li> <li><a href="#index-function_002c-generic-193">function, generic</a>: <a href="#Method-dispatching">Method dispatching</a></li> <li><a href="#index-function_002c-generic-192">function, generic</a>: <a href="#Inheritance">Inheritance</a></li> <li><a href="#index-function_002c-generic-187">function, generic</a>: <a href="#Definition">Definition</a></li> <li><a href="#index-function_002c-generic-185">function, generic</a>: <a href="#Object_002doriented-programming">Object-oriented programming</a></li> <li><a href="#index-function_002c-internal-204">function, internal</a>: <a href="#Group-methods">Group methods</a></li> <li><a href="#index-function_002c-internal-169">function, internal</a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-function_002c-modeling-83">function, modeling</a>: <a href="#Factors">Factors</a></li> <li><a href="#index-identifier-285">identifier</a>: <a href="#Identifiers">Identifiers</a></li> <li><a href="#index-index-119">index</a>: <a href="#Indexing-matrices-and-arrays">Indexing matrices and arrays</a></li> <li><a href="#index-index-116">index</a>: <a href="#Indexing-by-vectors">Indexing by vectors</a></li> <li><a href="#index-index-115">index</a>: <a href="#Indexing">Indexing</a></li> <li><a href="#index-index-19">index</a>: <a href="#List-objects">List objects</a></li> <li><a href="#index-index-15">index</a>: <a href="#Vector-objects">Vector objects</a></li> <li><a href="#index-mode-32">mode</a>: <a href="#Symbol-objects">Symbol objects</a></li> <li><a href="#index-mode-17">mode</a>: <a href="#Vector-objects">Vector objects</a></li> <li><a href="#index-mode-8">mode</a>: <a href="#Objects">Objects</a></li> <li><a href="#index-modeling-function-84">modeling function</a>: <a href="#Factors">Factors</a></li> <li><a href="#index-name-272">name</a>: <a href="#Debugging">Debugging</a></li> <li><a href="#index-name-208">name</a>: <a href="#Direct-manipulation-of-language-objects">Direct manipulation of language objects</a></li> <li><a href="#index-name-203">name</a>: <a href="#NextMethod">NextMethod</a></li> <li><a href="#index-name-194">name</a>: <a href="#Method-dispatching">Method dispatching</a></li> <li><a href="#index-name-160">name</a>: <a href="#Argument-evaluation">Argument evaluation</a></li> <li><a href="#index-name-154">name</a>: <a href="#Argument-matching">Argument matching</a></li> <li><a href="#index-name-148">name</a>: <a href="#Arguments">Arguments</a></li> <li><a href="#index-name-124">name</a>: <a href="#Scope-of-variables">Scope of variables</a></li> <li><a href="#index-name-104">name</a>: <a href="#Propagation-of-names">Propagation of names</a></li> <li><a href="#index-name-86">name</a>: <a href="#Symbol-lookup">Symbol lookup</a></li> <li><a href="#index-name-30">name</a>: <a href="#Symbol-objects">Symbol objects</a></li> <li><a href="#index-name-22">name</a>: <a href="#Language-objects">Language objects</a></li> <li><a href="#index-namespace-140">namespace</a>: <a href="#Search-path">Search path</a></li> <li><a href="#index-object-195">object</a>: <a href="#Method-dispatching">Method dispatching</a></li> <li><a href="#index-object-71">object</a>: <a href="#Attributes">Attributes</a></li> <li><a href="#index-object-29">object</a>: <a href="#Symbol-objects">Symbol objects</a></li> <li><a href="#index-object-3">object</a>: <a href="#Objects">Objects</a></li> <li><a href="#index-object_002doriented-186">object-oriented</a>: <a href="#Definition">Definition</a></li> <li><a href="#index-object_002doriented-183">object-oriented</a>: <a href="#Object_002doriented-programming">Object-oriented programming</a></li> <li><a href="#index-parsing-281">parsing</a>: <a href="#Internal-representation">Internal representation</a></li> <li><a href="#index-parsing-280">parsing</a>: <a href="#Parser">Parser</a></li> <li><a href="#index-parsing-213">parsing</a>: <a href="#Substitutions">Substitutions</a></li> <li><a href="#index-parsing-209">parsing</a>: <a href="#Direct-manipulation-of-language-objects">Direct manipulation of language objects</a></li> <li><a href="#index-parsing-207">parsing</a>: <a href="#Computing-on-the-language">Computing on the language</a></li> <li><a href="#index-parsing-85">parsing</a>: <a href="#Evaluation-of-expressions">Evaluation of expressions</a></li> <li><a href="#index-parsing-36">parsing</a>: <a href="#Symbol-objects">Symbol objects</a></li> <li><a href="#index-parsing-27">parsing</a>: <a href="#Language-objects">Language objects</a></li> <li><a href="#index-partial-matching-117">partial matching</a>: <a href="#Indexing-by-vectors">Indexing by vectors</a></li> <li><a href="#index-promise-57">promise</a>: <a href="#Promise-objects">Promise objects</a></li> <li><a href="#index-scope-218">scope</a>: <a href="#More-on-evaluation">More on evaluation</a></li> <li><a href="#index-scope-170">scope</a>: <a href="#Scope">Scope</a></li> <li><a href="#index-scope-134">scope</a>: <a href="#Stacks">Stacks</a></li> <li><a href="#index-scope-123">scope</a>: <a href="#Scope-of-variables">Scope of variables</a></li> <li><a href="#index-search-path-139">search path</a>: <a href="#Search-path">Search path</a></li> <li><a href="#index-statement-23">statement</a>: <a href="#Language-objects">Language objects</a></li> <li><a href="#index-symbol-224">symbol</a>: <a href="#Manipulation-of-function-calls">Manipulation of function calls</a></li> <li><a href="#index-symbol-212">symbol</a>: <a href="#Substitutions">Substitutions</a></li> <li><a href="#index-symbol-172">symbol</a>: <a href="#Scope">Scope</a></li> <li><a href="#index-symbol-87">symbol</a>: <a href="#Symbol-lookup">Symbol lookup</a></li> <li><a href="#index-symbol-28">symbol</a>: <a href="#Symbol-objects">Symbol objects</a></li> <li><a href="#index-token-37">token</a>: <a href="#Expression-objects">Expression objects</a></li> <li><a href="#index-type-108">type</a>: <a href="#NA-handling">NA handling</a></li> <li><a href="#index-type-80">type</a>: <a href="#Names">Names</a></li> <li><a href="#index-type-16">type</a>: <a href="#Vector-objects">Vector objects</a></li> <li><a href="#index-type-13">type</a>: <a href="#Basic-types">Basic types</a></li> <li><a href="#index-type-5">type</a>: <a href="#Objects">Objects</a></li> <li><a href="#index-value-89">value</a>: <a href="#Symbol-lookup">Symbol lookup</a></li> <li><a href="#index-variable-2">variable</a>: <a href="#Objects">Objects</a></li> <li><a href="#index-vector-95">vector</a>: <a href="#Operators">Operators</a></li> <li><a href="#index-vector-81">vector</a>: <a href="#Dimensions">Dimensions</a></li> <li><a href="#index-vector-14">vector</a>: <a href="#Vector-objects">Vector objects</a></li> </ul><div class="node"> <a name="References"></a> <p><hr> Previous: <a rel="previous" accesskey="p" href="#Concept-Index">Concept Index</a>, Up: <a rel="up" accesskey="u" href="#Top">Top</a> </div> <h2 class="appendix">Appendix A References</h2> <p>Richard A. Becker, John M. Chambers and Allan R. Wilks (1988), <em>The New S Language.</em> Chapman & Hall, New York. This book is often called the “<em>Blue Book</em>”. <div class="footnote"> <hr> <a name="texinfo-footnotes-in-document"></a><h4>Footnotes</h4><p class="footnote"><small>[<a name="fn-1" href="#fnd-1">1</a>]</small> actually two, but this draft manual predates the <strong>methods</strong> package.</p> <p class="footnote"><small>[<a name="fn-2" href="#fnd-2">2</a>]</small> Evaluation always takes place in an <a name="index-environment-297"></a>environment. See <a href="#Scope-of-variables">Scope of variables</a> for more details.</p> <p class="footnote"><small>[<a name="fn-3" href="#fnd-3">3</a>]</small> Looping is the repeated evaluation of a statement or block of statements.</p> <p class="footnote"><small>[<a name="fn-4" href="#fnd-4">4</a>]</small> such as <code>U+A0</code>, non-breaking space, and <code>U+3000</code>, ideographic space.</p> <hr></div> </body></html> <!-- Local Variables: coding: iso-8859-1 End: -->