<li><aname="toc-Computing-on-the-language-1"href="#Computing-on-the-language">6 Computing on the language</a>
<ulclass="no-bullet">
<li><aname="toc-Direct-manipulation-of-language-objects-1"href="#Direct-manipulation-of-language-objects">6.1 Direct manipulation of language objects</a></li>
<li><aname="toc-References-1"href="#References">Appendix A References</a></li>
</ul>
</div>
<aname="Top"></a>
<divclass="header">
<p>
Next: <ahref="#Introduction"accesskey="n"rel="next">Introduction</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="R-Language-Definition"></a>
<h1class="top">R Language Definition</h1>
<p>This is an introduction to the R language, explaining evaluation,
parsing, object oriented programming, computing on the language, and so
<tr><tdalign="left"valign="top">•<ahref="#Evaluation-of-expressions"accesskey="3">Evaluation of expressions</a>:</td><td> </td><tdalign="left"valign="top">
<tr><tdalign="left"valign="top">•<ahref="#Computing-on-the-language"accesskey="6">Computing on the language</a>:</td><td> </td><tdalign="left"valign="top">
</td></tr>
<tr><tdalign="left"valign="top">•<ahref="#System-and-foreign-language-interfaces"accesskey="7">System and foreign language interfaces</a>:</td><td> </td><tdalign="left"valign="top">
<tr><tdalign="left"valign="top">•<ahref="#Function-and-Variable-Index">Function and Variable Index</a>:</td><td> </td><tdalign="left"valign="top">
<tr><tdalign="left"valign="top">•<ahref="#Builtin-objects-and-special-forms"accesskey="7">Builtin objects and special forms</a>:</td><td> </td><tdalign="left"valign="top">
<p>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
<aname="index-environment"></a>
environment. The argument list is a comma-separated list of
arguments. An
<aname="index-argument"></a>
argument can be a symbol, or a ‘<samp><var>symbol</var> =
<var>default</var></samp>’ construct, or the special argument ‘<samp>...</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>...</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>
<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>
<p>A function’s
<aname="index-function-1"></a>
<aname="index-environment-1"></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>
<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
<aname="index-assignment"></a>
assignments).
<aname="index-formals"></a>
<aname="index-body"></a>
<aname="index-environment-20"></a>
The last of these can be used to remove unwanted environment capture.
</p>
<p>When a function is called, a new environment (called the
<em>evaluation environment</em>) is created, whose enclosure (see
<ahref="#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>
<aname="index-function-2"></a>
<p>There is also a facility for converting functions to and from list
structures using <code>as.list</code> and <code>as.function</code>.
<aname="index-as_002efunction"></a>
These have been included to provide compatibility with S and their
use is discouraged.
</p>
<hr>
<aname="NULL-object"></a>
<divclass="header">
<p>
Next: <ahref="#Builtin-objects-and-special-forms"accesskey="n"rel="next">Builtin objects and special forms</a>, Previous: <ahref="#Function-objects"accesskey="p"rel="prev">Function objects</a>, Up: <ahref="#Basic-types"accesskey="u"rel="up">Basic types</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="NULL"></a>
<h4class="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.
<aname="index-NULL"></a>
</p>
<p>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
<h4class="subsection">2.1.7 Builtin objects and special forms</h4>
<p>These two kinds of object contain the builtin
<aname="index-function-3"></a>
<aname="index-_002ePrimitive"></a>
<aname="index-_002eInternal"></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>
<p>From the R language, these objects are just another kind of function.
The <code>is.primitive</code> function can distinguish them from interpreted
<aname="index-function-4"></a>
functions.
</p>
<hr>
<aname="Promise-objects"></a>
<divclass="header">
<p>
Next: <ahref="#Dot_002ddot_002ddot"accesskey="n"rel="next">Dot-dot-dot</a>, Previous: <ahref="#Builtin-objects-and-special-forms"accesskey="p"rel="prev">Builtin objects and special forms</a>, Up: <ahref="#Basic-types"accesskey="u"rel="up">Basic types</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Promise-objects-1"></a>
<h4class="subsection">2.1.8 Promise objects</h4>
<aname="index-promise"></a>
<p>Promise objects are part of R’s lazy evaluation mechanism. They
contain three slots: a value, an expression, and an
<aname="index-environment-2"></a>
environment. When a
<aname="index-function-5"></a>
<aname="index-function-argument"></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>
<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
<aname="index-evaluation_002c-expression-1"></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>
<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
<tr><tdalign="left"valign="top">•<ahref="#Time-series-attributes"accesskey="5">Time series attributes</a>:</td><td> </td><tdalign="left"valign="top">
</td></tr>
<tr><tdalign="left"valign="top">•<ahref="#Copying-of-attributes"accesskey="6">Copying of attributes</a>:</td><td> </td><tdalign="left"valign="top">
</td></tr>
</table>
<hr>
<aname="Names"></a>
<divclass="header">
<p>
Next: <ahref="#Dimensions"accesskey="n"rel="next">Dimensions</a>, Previous: <ahref="#Attributes"accesskey="p"rel="prev">Attributes</a>, Up: <ahref="#Attributes"accesskey="u"rel="up">Attributes</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Names-1"></a>
<h4class="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>
<p>One may get and set the names using <code>names</code> and <code>names<-</code>
constructions.
<aname="index-names"></a>
<aname="index-names_003c_002d"></a>
<aname="index-type-4"></a>
The latter will perform the necessary consistency checks to ensure that
the names attribute has the proper type and length.
</p>
<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>.
</p>
<hr>
<aname="Dimensions"></a>
<divclass="header">
<p>
Next: <ahref="#Dimnames"accesskey="n"rel="next">Dimnames</a>, Previous: <ahref="#Names"accesskey="p"rel="prev">Names</a>, Up: <ahref="#Attributes"accesskey="u"rel="up">Attributes</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Dimensions-1"></a>
<h4class="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>
<aname="index-vector-1"></a>
<p>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.
</p>
<hr>
<aname="Dimnames"></a>
<divclass="header">
<p>
Next: <ahref="#Classes"accesskey="n"rel="next">Classes</a>, Previous: <ahref="#Dimensions"accesskey="p"rel="prev">Dimensions</a>, Up: <ahref="#Attributes"accesskey="u"rel="up">Attributes</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Dimnames-1"></a>
<h4class="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.
</p>
<hr>
<aname="Classes"></a>
<divclass="header">
<p>
Next: <ahref="#Time-series-attributes"accesskey="n"rel="next">Time series attributes</a>, Previous: <ahref="#Dimnames"accesskey="p"rel="prev">Dimnames</a>, Up: <ahref="#Attributes"accesskey="u"rel="up">Attributes</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Classes-1"></a>
<h4class="subsection">2.2.4 Classes</h4>
<p>R has an elaborate class system<aname="DOCF1"href="#FOOT1"><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>
<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
<aname="index-coercion-3"></a>
coercion functions should be preferred.
</p>
<hr>
<aname="Time-series-attributes"></a>
<divclass="header">
<p>
Next: <ahref="#Copying-of-attributes"accesskey="n"rel="next">Copying of attributes</a>, Previous: <ahref="#Classes"accesskey="p"rel="prev">Classes</a>, Up: <ahref="#Attributes"accesskey="u"rel="up">Attributes</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Time-series-attributes-1"></a>
<h4class="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.
</p>
<hr>
<aname="Copying-of-attributes"></a>
<divclass="header">
<p>
Previous: <ahref="#Time-series-attributes"accesskey="p"rel="prev">Time series attributes</a>, Up: <ahref="#Attributes"accesskey="u"rel="up">Attributes</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Copying-of-attributes-1"></a>
<h4class="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>
<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>
<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>
<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>
<p>The default method for sorting drops all attributes except names, which
are sorted along with the object.
</p>
<hr>
<aname="Special-compound-objects"></a>
<divclass="header">
<p>
Previous: <ahref="#Attributes"accesskey="p"rel="prev">Attributes</a>, Up: <ahref="#Objects"accesskey="u"rel="up">Objects</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Special-compound-objects-1"></a>
<h3class="section">2.3 Special compound objects</h3>
<tr><tdalign="left"valign="top">•<ahref="#Scope-of-variables"accesskey="5">Scope of variables</a>:</td><td> </td><tdalign="left"valign="top">
</td></tr>
</table>
<hr>
<aname="Simple-evaluation"></a>
<divclass="header">
<p>
Next: <ahref="#Control-structures"accesskey="n"rel="next">Control structures</a>, Previous: <ahref="#Evaluation-of-expressions"accesskey="p"rel="prev">Evaluation of expressions</a>, Up: <ahref="#Evaluation-of-expressions"accesskey="u"rel="up">Evaluation of expressions</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
<tr><tdalign="left"valign="top">•<ahref="#Propagation-of-names"accesskey="2">Propagation of names</a>:</td><td> </td><tdalign="left"valign="top">
<p>(matrix+matrix, dimensions must match. vector+matrix: first recycle,
then check if dims fit, error if not)
</p>
<hr>
<aname="NA-handling"></a>
<divclass="header">
<p>
Previous: <ahref="#Dimensional-attributes"accesskey="p"rel="prev">Dimensional attributes</a>, Up: <ahref="#Elementary-arithmetic-operations"accesskey="u"rel="up">Elementary arithmetic operations</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="NA-handling-1"></a>
<h4class="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 <ahref="#Arguments">Arguments</a>).
<aname="index-missing"></a>
<aname="index-NA"></a>
<aname="index-NaN"></a>
</p>
<aname="index-type-5"></a>
<p>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
<ahref="#Indexing">Indexing</a> for details).
</p>
<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>FALSE & NA</samp>’ is <code>FALSE</code>,
‘<samp>TRUE | NA</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>.
<aname="index-is_002ena"></a>
However, an <code>NA</code> value will match another <code>NA</code> value in
<code>match</code>.
</p>
<p>Numeric calculations whose result is undefined, such as ‘<samp>0/0</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
<aname="index-is_002enan"></a>
<code>NaN</code>, <code>is.na</code> also returns <code>TRUE</code> for <code>NaN</code>.
<aname="index-coercion-4"></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>
<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>as.character(NA)</samp>’ rather than <code>"NA"</code>, or
set elements to <code>NA</code> using <code>is.na<-</code>.
</p>
<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>
<p>There is no <code>NA</code> value for raw vectors.
</p>
<hr>
<aname="Indexing"></a>
<divclass="header">
<p>
Next: <ahref="#Scope-of-variables"accesskey="n"rel="next">Scope of variables</a>, Previous: <ahref="#Elementary-arithmetic-operations"accesskey="p"rel="prev">Elementary arithmetic operations</a>, Up: <ahref="#Evaluation-of-expressions"accesskey="u"rel="up">Evaluation of expressions</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Indexing-1"></a>
<h3class="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>
<p>R has three basic indexing operators, with syntax displayed by the
following examples
</p>
<divclass="example">
<preclass="example">x[i]
x[i, j]
x[[i]]
x[[i, j]]
x$a
x$"a"
</pre></div>
<aname="index-_005b"></a>
<aname="index-_005b_005b"></a>
<aname="index-_0024"></a>
<aname="index-index-2"></a>
<p>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>
<p>For lists, one generally uses <code>[[</code> to select any single element,
whereas <code>[</code> returns a list of the selected elements.
</p>
<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>
<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.
<tr><tdalign="left"valign="top">•<ahref="#Indexing-by-vectors"accesskey="1">Indexing by vectors</a>:</td><td> </td><tdalign="left"valign="top">
</td></tr>
<tr><tdalign="left"valign="top">•<ahref="#Indexing-matrices-and-arrays"accesskey="2">Indexing matrices and arrays</a>:</td><td> </td><tdalign="left"valign="top">
</td></tr>
<tr><tdalign="left"valign="top">•<ahref="#Indexing-other-structures"accesskey="3">Indexing other structures</a>:</td><td> </td><tdalign="left"valign="top">
Next: <ahref="#Indexing-matrices-and-arrays"accesskey="n"rel="next">Indexing matrices and arrays</a>, Previous: <ahref="#Indexing"accesskey="p"rel="prev">Indexing</a>, Up: <ahref="#Indexing"accesskey="u"rel="up">Indexing</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Indexing-by-vectors-1"></a>
<h4class="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>.
</p>
<ul>
<li><aname="index-index-3"></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>. Negative out of bounds values
for <code>i</code> are silently disregarded since R version 2.6.0, S compatibly,
as they mean to drop non-existing elements and that is an empty operation
(“no-op”).
</p>
<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.
</p>
</li><li><strong>Other numeric</strong>. Non-integer values are converted to integer
(by truncation towards zero) before use.
</li><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 <ahref="#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>.
</li><li><aname="index-partial-matching"></a>
<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><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><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><li><strong>NULL</strong>. This is treated as if it were <code>integer(0)</code>.
</li></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>.
<aname="index-NA-1"></a>
</p>
<p>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>
<p>Indexing with <code>[</code> will also carry out the relevant subsetting of
any names attributes.
</p>
<hr>
<aname="Indexing-matrices-and-arrays"></a>
<divclass="header">
<p>
Next: <ahref="#Indexing-other-structures"accesskey="n"rel="next">Indexing other structures</a>, Previous: <ahref="#Indexing-by-vectors"accesskey="p"rel="prev">Indexing by vectors</a>, Up: <ahref="#Indexing"accesskey="u"rel="up">Indexing</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Indexing-matrices-and-arrays-1"></a>
<h4class="subsection">3.4.2 Indexing matrices and arrays</h4>
<aname="index-index-4"></a>
<p>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>
<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>
<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
<p>Indexing matrices may not contain negative indices. <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>
<p>Both in the case of using a single
<aname="index-index-5"></a>
index and in matrix indexing, a <code>names</code> attribute is used if
present, as had the structure been one-dimensional.
</p>
<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>drop = FALSE</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 <em>1</em> by <em>n</em> 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>drop
= FALSE</samp>’ is used.
</p>
<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>
<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.
</p>
<hr>
<aname="Indexing-other-structures"></a>
<divclass="header">
<p>
Next: <ahref="#Subset-assignment"accesskey="n"rel="next">Subset assignment</a>, Previous: <ahref="#Indexing-matrices-and-arrays"accesskey="p"rel="prev">Indexing matrices and arrays</a>, Up: <ahref="#Indexing"accesskey="u"rel="up">Indexing</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Indexing-other-structures-1"></a>
<h4class="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>
<p>The most important example of a class method for <code>[</code> is that used
for data frames. It is not 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>
<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.
</p>
<hr>
<aname="Subset-assignment"></a>
<divclass="header">
<p>
Previous: <ahref="#Indexing-other-structures"accesskey="p"rel="prev">Indexing other structures</a>, Up: <ahref="#Indexing"accesskey="u"rel="up">Indexing</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
<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.
</p>
<hr>
<aname="Scope-of-variables"></a>
<divclass="header">
<p>
Previous: <ahref="#Indexing"accesskey="p"rel="prev">Indexing</a>, Up: <ahref="#Evaluation-of-expressions"accesskey="u"rel="up">Evaluation of expressions</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Scope-of-variables-1"></a>
<h3class="section">3.5 Scope of variables</h3>
<aname="index-scope"></a>
<aname="index-name-4"></a>
<p>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>
<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.
Next: <ahref="#Lexical-environment"accesskey="n"rel="next">Lexical environment</a>, Previous: <ahref="#Scope-of-variables"accesskey="p"rel="prev">Scope of variables</a>, Up: <ahref="#Scope-of-variables"accesskey="u"rel="up">Scope of variables</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Global-environment-1"></a>
<h4class="subsection">3.5.1 Global environment</h4>
<p>The global
<aname="index-environment-5"></a>
environment is the root of the user workspace. An
<aname="index-assignment-4"></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.
</p>
<hr>
<aname="Lexical-environment"></a>
<divclass="header">
<p>
Next: <ahref="#Stacks"accesskey="n"rel="next">Stacks</a>, Previous: <ahref="#Global-environment"accesskey="p"rel="prev">Global environment</a>, Up: <ahref="#Scope-of-variables"accesskey="u"rel="up">Scope of variables</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
variables created in the function, and is evaluated in an environment,
which in combination creates a new environment.
</p>
<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>
<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>
<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
<aname="index-environment_002c-evaluation"></a>
evaluation environment is created with the closure’s environment as
enclosure. Notice that this is not
necessarily the environment of the caller!
</p>
<p>Thus, when a variable is requested inside a
<aname="index-function-9"></a>
function, it is first sought
in the
<aname="index-environment_002c-evaluation-1"></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.
</p>
<hr>
<aname="Stacks"></a>
<divclass="header">
<p>
Next: <ahref="#Search-path"accesskey="n"rel="next">Search path</a>, Previous: <ahref="#Lexical-environment"accesskey="p"rel="prev">Lexical environment</a>, Up: <ahref="#Scope-of-variables"accesskey="u"rel="up">Scope of variables</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="The-call-stack"></a>
<h4class="subsection">3.5.3 The call stack</h4>
<p>Every time a
<aname="index-function-10"></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>
<p>Making variables defined higher up the call stack available is called
<aname="index-scope-1"></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
<aname="index-environment-7"></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>
<p>Access to the
<aname="index-call-stack"></a>
call stack is provided through a family of functions which
have names that start with ‘<samp>sys.</samp>’. They are listed briefly below.
</p>
<aname="index-evaluation"></a>
<dlcompact="compact">
<dt><code>sys.call</code></dt>
<dd><p>Get the call for the specified context.
</p></dd>
<dt><code>sys.frame</code></dt>
<dd><p>Get the evaluation frame for the specified context.
</p></dd>
<dt><code>sys.nframe</code></dt>
<dd><p>Get the environment frame for all active contexts.
</p></dd>
<dt><code>sys.function</code></dt>
<dd><p>Get the function being invoked in the specified context.
</p></dd>
<dt><code>sys.parent</code></dt>
<dd><p>Get the parent of the current function invocation.
</p></dd>
<dt><code>sys.calls</code></dt>
<dd><p>Get the calls for all the active contexts.
</p></dd>
<dt><code>sys.frames</code></dt>
<dd><p>Get the evaluation frames for all the active contexts.
</p></dd>
<dt><code>sys.parents</code></dt>
<dd><p>Get the numeric labels for all active contexts.
</p></dd>
<dt><code>sys.on.exit</code></dt>
<dd><p>Set a function to be executed when the specified context is exited.
</p></dd>
<dt><code>sys.status</code></dt>
<dd><p>Calls <code>sys.frames</code>, <code>sys.parents</code> and <code>sys.calls</code>.
</p></dd>
<dt><code>parent.frame</code></dt>
<dd><p>Get the evaluation frame for the specified parent context.
</p></dd>
</dl>
<hr>
<aname="Search-path"></a>
<divclass="header">
<p>
Previous: <ahref="#Stacks"accesskey="p"rel="prev">Stacks</a>, Up: <ahref="#Scope-of-variables"accesskey="u"rel="up">Scope of variables</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Search-path-1"></a>
<h4class="subsection">3.5.4 Search path</h4>
<p>In addition to the evaluation
<aname="index-environment-8"></a>
<aname="index-search-path"></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>
<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>
<aname="index-namespace"></a>
<p>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.
</p>
<hr>
<aname="Functions"></a>
<divclass="header">
<p>
Next: <ahref="#Object_002doriented-programming"accesskey="n"rel="next">Object-oriented programming</a>, Previous: <ahref="#Evaluation-of-expressions"accesskey="p"rel="prev">Evaluation of expressions</a>, Up: <ahref="#Top"accesskey="u"rel="up">Top</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
<tr><tdalign="left"valign="top">•<ahref="#Functions-as-objects"accesskey="2">Functions as objects</a>:</td><td> </td><tdalign="left"valign="top">
<tr><tdalign="left"valign="top">•<ahref="#Syntax-and-examples"accesskey="1">Syntax and examples</a>:</td><td> </td><tdalign="left"valign="top">
<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>
<p>An
<aname="index-argument-1"></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> = <var>expression</var></samp>’, or the special formal argument
‘<samp>...</samp>’.
</p>
<p>The <em>body</em> can be any valid R expression. Generally, the body
is a group of expressions contained in curly braces (‘<samp>{</samp>’ and
‘<samp>}</samp>’).
</p>
<p>Generally
<aname="index-function-13"></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
<aname="index-function_002c-anonymous"></a>
anonymous
function. Anonymous functions are most frequently used as arguments to
other functions such as the <code>apply</code> family or <code>outer</code>.
</p>
<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.
</p>
<hr>
<aname="Arguments"></a>
<divclass="header">
<p>
Previous: <ahref="#Syntax-and-examples"accesskey="p"rel="prev">Syntax and examples</a>, Up: <ahref="#Writing-functions"accesskey="u"rel="up">Writing functions</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Arguments-1"></a>
<h4class="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>
<aname="index-argument_002c-default-values"></a>
<p>Default values for arguments can be specified using the special form
‘<samp><var>name</var> = <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
<aname="index-evaluation_002c-expression-2"></a>
evaluated in the evaluation
frame of the function.
</p>
<p>Default behaviours can also be specified by using the function
<code>missing</code>. When <code>missing</code> is called with the
<aname="index-name-5"></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>
<p>The special type of argument ‘<samp>...</samp>’ can contain any number of
supplied arguments. It is used for a variety of purposes. It allows
you to write a
<aname="index-function-14"></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.
</p>
<hr>
<aname="Functions-as-objects"></a>
<divclass="header">
<p>
Next: <ahref="#Evaluation"accesskey="n"rel="next">Evaluation</a>, Previous: <ahref="#Writing-functions"accesskey="p"rel="prev">Writing functions</a>, Up: <ahref="#Functions"accesskey="u"rel="up">Functions</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Functions-as-objects-1"></a>
<h3class="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
<ahref="#Function-objects">Function objects</a> for the details.
</p>
<hr>
<aname="Evaluation"></a>
<divclass="header">
<p>
Previous: <ahref="#Functions-as-objects"accesskey="p"rel="prev">Functions as objects</a>, Up: <ahref="#Functions"accesskey="u"rel="up">Functions</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
<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.
</p>
<hr>
<aname="Scope"></a>
<divclass="header">
<p>
Previous: <ahref="#Argument-evaluation"accesskey="p"rel="prev">Argument evaluation</a>, Up: <ahref="#Evaluation"accesskey="u"rel="up">Evaluation</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Scope-1"></a>
<h4class="subsection">4.3.4 Scope</h4>
<aname="index-scope-2"></a>
<p>Scope or the scoping rules are simply the set of rules used by the
<aname="index-evaluation_002c-symbol-2"></a>
evaluator to find a value for a
<aname="index-symbol-3"></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>
<p>R adheres to a set of rules that are called <em>lexical scope</em>.
This means the variable
<aname="index-binding"></a>
bindings in effect at the time the expression
was created are used to provide values for any unbound symbols in the
expression.
</p>
<p>Most of the interesting properties of
<aname="index-scope-3"></a>
scope are involved with evaluating
<aname="index-function-21"></a>
functions and we concentrate on this issue. A symbol can be either
<aname="index-binding-1"></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
<aname="index-assignment-6"></a>
assignment.
</p>
<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
<aname="index-environment-12"></a>
environment of the function is searched
first, then its enclosure and so on until the global environment is reached.
</p>
<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>
<p>When this set of rules is combined with the fact that
<aname="index-function-22"></a>
functions can be
returned as values from other functions then some rather nice, but at
first glance peculiar, properties obtain.
</p>
<p>A simple example:
</p>
<divclass="example">
<preclass="example">f <- function() {
y <- 10
g <- function(x) x + y
return(g)
}
h <- f()
h(3)
</pre></div>
<aname="index-evaluation-3"></a>
<p>A rather interesting question is what happens when <code>h</code> is
evaluated. To describe this we need a bit more notation. Within a
<aname="index-function-23"></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>
<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
<aname="index-scope-4"></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>
<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.
</p>
<hr>
<aname="Object_002doriented-programming"></a>
<divclass="header">
<p>
Next: <ahref="#Computing-on-the-language"accesskey="n"rel="next">Computing on the language</a>, Previous: <ahref="#Functions"accesskey="p"rel="prev">Functions</a>, Up: <ahref="#Top"accesskey="u"rel="up">Top</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
<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>
<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>.
</p>
<hr>
<aname="Writing-methods"></a>
<divclass="header">
<p>
Previous: <ahref="#Group-methods"accesskey="p"rel="prev">Group methods</a>, Up: <ahref="#Object_002doriented-programming"accesskey="u"rel="up">Object-oriented programming</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Writing-methods-1"></a>
<h3class="section">5.7 Writing methods</h3>
<p>Users can easily write their own methods and generic functions. A
<aname="index-function_002c-generic-6"></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>
<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>
<p>The most common use of
<aname="index-function_002c-generic-7"></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.
</p>
<hr>
<aname="Computing-on-the-language"></a>
<divclass="header">
<p>
Next: <ahref="#System-and-foreign-language-interfaces"accesskey="n"rel="next">System and foreign language interfaces</a>, Previous: <ahref="#Object_002doriented-programming"accesskey="p"rel="prev">Object-oriented programming</a>, Up: <ahref="#Top"accesskey="u"rel="up">Top</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Computing-on-the-language-1"></a>
<h2class="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>
<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
<aname="index-parsing-3"></a>
parsed expressions and functions and allows you to alter and
subsequently execute them, or create entirely new functions from
scratch.
</p>
<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>
<p>In this chapter, we give an introduction to the set of facilities that
<tr><tdalign="left"valign="top">•<ahref="#Direct-manipulation-of-language-objects"accesskey="1">Direct manipulation of language objects</a>:</td><td> </td><tdalign="left"valign="top">
<tr><tdalign="left"valign="top">•<ahref="#More-on-evaluation"accesskey="3">More on evaluation</a>:</td><td> </td><tdalign="left"valign="top">
</td></tr>
<tr><tdalign="left"valign="top">•<ahref="#Evaluation-of-expression-objects"accesskey="4">Evaluation of expression objects</a>:</td><td> </td><tdalign="left"valign="top">
</td></tr>
<tr><tdalign="left"valign="top">•<ahref="#Manipulation-of-function-calls"accesskey="5">Manipulation of function calls</a>:</td><td> </td><tdalign="left"valign="top">
</td></tr>
<tr><tdalign="left"valign="top">•<ahref="#Manipulation-of-functions"accesskey="6">Manipulation of functions</a>:</td><td> </td><tdalign="left"valign="top">
Next: <ahref="#Substitutions"accesskey="n"rel="next">Substitutions</a>, Previous: <ahref="#Computing-on-the-language"accesskey="p"rel="prev">Computing on the language</a>, Up: <ahref="#Computing-on-the-language"accesskey="u"rel="up">Computing on the language</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
notation. In evaluations, the ‘<samp>(</samp>’ operator just returns its
argument.
</p>
<p>This is a bit unfortunate, but it is not easy to write a
<aname="index-parsing-4"></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>
<p>As it happens, R’s parser is not perfectly invertible, nor is its
deparser, as the following examples show
</p>
<divclass="example">
<preclass="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></div>
<p>Deparsed expressions should, however, evaluate to an equivalent value
to the original expression (up to rounding error).
</p>
<p>...internal storage of flow control constructs...note Splus
incompatibility...
</p>
<hr>
<aname="Substitutions"></a>
<divclass="header">
<p>
Next: <ahref="#More-on-evaluation"accesskey="n"rel="next">More on evaluation</a>, Previous: <ahref="#Direct-manipulation-of-language-objects"accesskey="p"rel="prev">Direct manipulation of language objects</a>, Up: <ahref="#Computing-on-the-language"accesskey="u"rel="up">Computing on the language</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Substitutions-1"></a>
<h3class="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>:
<aname="index-substitute"></a>
</p>
<divclass="example">
<preclass="example">xlabel <- if (!missing(x))
deparse(substitute(x))
</pre></div>
<p>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>
<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
<aname="index-evaluation_002c-lazy-1"></a>
lazy evaluation scheme of R
(see <ahref="#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>
<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:
</p>
<divclass="example">
<preclass="example">> substitute(a + b, list(a = 1, b = quote(x)))
1 + x
</pre></div>
<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
</p>
<divclass="example">
<preclass="example">> plot(0)
> for (i in 1:4)
+ text(1, 0.2 * i,
+ substitute(x[ix] == y, list(ix = i, y = pnorm(i))))
</pre></div>
<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
<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>
<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
</p><divclass="example">
<preclass="example">> plot(0)
> for (i in 1:4)
+ text(1, 0.2 * i,
+ substitute(x[ix] == y, list(ix = i, y = pnorm(i))))
</pre></div>
<p>could be written more compactly as
</p><divclass="example">
<preclass="example">plot(0)
for(i in 1:4)
text(1, 0.2*i, bquote( x[.(i)] == .(pnorm(i)) ))
</pre></div>
<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.
</p>
<hr>
<aname="More-on-evaluation"></a>
<divclass="header">
<p>
Next: <ahref="#Evaluation-of-expression-objects"accesskey="n"rel="next">Evaluation of expression objects</a>, Previous: <ahref="#Substitutions"accesskey="p"rel="prev">Substitutions</a>, Up: <ahref="#Computing-on-the-language"accesskey="u"rel="up">Computing on the language</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="More-on-evaluation-1"></a>
<h3class="section">6.3 More on evaluation</h3>
<aname="index-evaluation-6"></a>
<p>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
<aname="index-environment-15"></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.
<aname="index-eval"></a>
</p>
<p>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
<aname="index-scope-5"></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>
<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
<p>This is also true when evaluating in lists, but the original list does
not change because one is really working on a copy.
</p>
<hr>
<aname="Evaluation-of-expression-objects"></a>
<divclass="header">
<p>
Next: <ahref="#Manipulation-of-function-calls"accesskey="n"rel="next">Manipulation of function calls</a>, Previous: <ahref="#More-on-evaluation"accesskey="p"rel="prev">More on evaluation</a>, Up: <ahref="#Computing-on-the-language"accesskey="u"rel="up">Computing on the language</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Evaluation-of-expression-objects-1"></a>
<h3class="section">6.4 Evaluation of expression objects</h3>
<p>Objects of mode <code>"expression"</code> are defined in <ahref="#Expression-objects">Expression objects</a>. They are very similar to lists of call objects.
</p>
<divclass="example">
<preclass="example">> ex <- expression(2 + 2, 3 + 4)
> ex[[1]]
2 + 2
> ex[[2]]
3 + 4
> eval(ex)
[1] 7
</pre></div>
<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
<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:
</p>
<divclass="example">
<preclass="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></div>
<p>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.
</p>
<hr>
<aname="Manipulation-of-function-calls"></a>
<divclass="header">
<p>
Next: <ahref="#Manipulation-of-functions"accesskey="n"rel="next">Manipulation of functions</a>, Previous: <ahref="#Evaluation-of-expression-objects"accesskey="p"rel="prev">Evaluation of expression objects</a>, Up: <ahref="#Computing-on-the-language"accesskey="u"rel="up">Computing on the language</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Manipulation-of-function-calls-1"></a>
<h3class="section">6.5 Manipulation of function calls</h3>
<p>It is possible for a
<aname="index-function-26"></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:
</p>
<divclass="example">
<preclass="example">> f <- function(x, y, ...) sys.call()
> f(y = 1, 2, z = 3, 4)
f(y = 1, 2, z = 3, 4)
</pre></div>
<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>
<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
</p>
<divclass="example">
<preclass="example">> f <- function(x, y, ...) match.call()
> f(y = 1, 2, z = 3, 4)
f(x = 2, y = 1, z = 3, 4)
</pre></div>
<p>Notice that the second argument now gets matched to <code>x</code> and appears
in the corresponding position in the result.
</p>
<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:
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></div>
<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>
<p>Two further functions exist for the construction of function calls,
namely <code>call</code> and <code>do.call</code>.
</p>
<p>The function <code>call</code> allows creation of a call object from the
function name and the list of arguments
</p>
<divclass="example">
<preclass="example">> x <- 10.5
> call("round", x)
round(10.5)
</pre></div>
<p>As seen, the value of <code>x</code> rather than the
<aname="index-symbol-5"></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>
<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.
<aname="index-do_002ecall"></a>
</p>
<divclass="example">
<preclass="example">is.na.data.frame <- function (x) {
y <- do.call("cbind", lapply(x, "is.na"))
rownames(y) <- row.names(x)
y
}
</pre></div>
<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.
</p>
<hr>
<aname="Manipulation-of-functions"></a>
<divclass="header">
<p>
Previous: <ahref="#Manipulation-of-function-calls"accesskey="p"rel="prev">Manipulation of function calls</a>, Up: <ahref="#Computing-on-the-language"accesskey="u"rel="up">Computing on the language</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Manipulation-of-functions-1"></a>
<h3class="section">6.6 Manipulation of functions</h3>
<p>It is often useful to be able to manipulate the components of a
<aname="index-function-27"></a>
function
or closure. R provides a set of interface functions for this
purpose.
</p>
<dlcompact="compact">
<dt><code>body</code>
<aname="index-body-1"></a>
</dt>
<dd><p>Returns the expression that is the body of the function.
</p></dd>
<dt><code>formals</code>
<aname="index-formals-1"></a>
</dt>
<dd><p>Returns a list of the formal arguments to the function. This is a
<code>pairlist</code>.
</p></dd>
<dt><code>environment</code>
<aname="index-environment-21"></a>
</dt>
<dd><aname="index-environment-16"></a>
<p>Returns the environment associated with the function.
</p></dd>
<dt><code>body<-</code>
<aname="index-body_003c_002d"></a>
</dt>
<dd><p>This sets the body of the function to the supplied expression.
</p></dd>
<dt><code>formals<-</code>
<aname="index-formals_003c_002d"></a>
</dt>
<dd><p>Sets the formal arguments of the function to the supplied list.
</p></dd>
<dt><code>environment<-</code>
<aname="index-environment_003c_002d"></a>
</dt>
<dd><p>Sets the environment of the function to the specified environment.
</p></dd>
</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>
<p>It is also possible to convert a
<aname="index-function-28"></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
Next: <ahref="#Exception-handling"accesskey="n"rel="next">Exception handling</a>, Previous: <ahref="#Computing-on-the-language"accesskey="p"rel="prev">Computing on the language</a>, Up: <ahref="#Top"accesskey="u"rel="up">Top</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
<tr><tdalign="left"valign="top">•<ahref="#Operating-system-access"accesskey="1">Operating system access</a>:</td><td> </td><tdalign="left"valign="top">
</td></tr>
<tr><tdalign="left"valign="top">•<ahref="#Foreign-language-interfaces"accesskey="2">Foreign language interfaces</a>:</td><td> </td><tdalign="left"valign="top">
</td></tr>
<tr><tdalign="left"valign="top">•<ahref="#g_t_002eInternal-and-_002ePrimitive"accesskey="3">.Internal and .Primitive</a>:</td><td> </td><tdalign="left"valign="top">
</td></tr>
</table>
<hr>
<aname="Operating-system-access"></a>
<divclass="header">
<p>
Next: <ahref="#Foreign-language-interfaces"accesskey="n"rel="next">Foreign language interfaces</a>, Previous: <ahref="#System-and-foreign-language-interfaces"accesskey="p"rel="prev">System and foreign language interfaces</a>, Up: <ahref="#System-and-foreign-language-interfaces"accesskey="u"rel="up">System and foreign language interfaces</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Operating-system-access-1"></a>
<h3class="section">7.1 Operating system access</h3>
<p>Access to the operating system shell is via the R function
<code>system</code>.
<aname="index-system"></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>
<p>The functions <code>system.time</code>
<aname="index-system_002etime"></a>
and <code>proc.time</code>
<aname="index-proc_002etime"></a>
are available for timing (although the information available may be
<tr><tdwidth="30%"><code>file.show</code></td><tdwidth="70%">Display a text file
<aname="index-file_002eshow"></a></td></tr>
<tr><tdwidth="30%"><code>unlink</code></td><tdwidth="70%">Remove files or directories.
<aname="index-unlink"></a></td></tr>
</table>
</blockquote>
<p>There are also functions for manipulating file names and paths in a
platform-independent way.
</p><blockquote>
<tablesummary="">
<tr><tdwidth="30%"><code>basename</code></td><tdwidth="70%">File name without directory
<aname="index-basename"></a></td></tr>
<tr><tdwidth="30%"><code>dirname</code></td><tdwidth="70%">Directory name
<aname="index-dirname"></a></td></tr>
<tr><tdwidth="30%"><code>file.path</code></td><tdwidth="70%">Construct path to file
<aname="index-file_002epath"></a></td></tr>
<tr><tdwidth="30%"><code>path.expand</code></td><tdwidth="70%">Expand <code>~</code> in Unix path
<aname="index-path_002eexpand"></a></td></tr>
</table>
</blockquote>
<hr>
<aname="Foreign-language-interfaces"></a>
<divclass="header">
<p>
Next: <ahref="#g_t_002eInternal-and-_002ePrimitive"accesskey="n"rel="next">.Internal and .Primitive</a>, Previous: <ahref="#Operating-system-access"accesskey="p"rel="prev">Operating system access</a>, Up: <ahref="#System-and-foreign-language-interfaces"accesskey="u"rel="up">System and foreign language interfaces</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Foreign-language-interfaces-1"></a>
<h3class="section">7.2 Foreign language interfaces</h3>
<aname="index-_002eC"></a>
<aname="index-_002eFortran"></a>
<aname="index-_002eCall"></a>
<aname="index-_002eExternal"></a>
<p>See <ahref="./R-exts.html#System-and-foreign-language-interfaces">System and foreign language interfaces</a> in <cite>Writing R
Extensions</cite> for the details of adding functionality to R via compiled
code.
</p>
<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>
<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.
</p>
<hr>
<aname="g_t_002eInternal-and-_002ePrimitive"></a>
<divclass="header">
<p>
Previous: <ahref="#Foreign-language-interfaces"accesskey="p"rel="prev">Foreign language interfaces</a>, Up: <ahref="#System-and-foreign-language-interfaces"accesskey="u"rel="up">System and foreign language interfaces</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
<h3class="section">7.3 .Internal and .Primitive</h3>
<aname="index-_002eInternal-1"></a>
<aname="index-_002ePrimitive-1"></a>
<p>The <code>.Internal</code> and <code>.Primitive</code> interfaces are used to call
<strong>C</strong> code compiled into R at build time.
See <ahref="./R-ints.html#g_t_002eInternal-vs-_002ePrimitive">.Internal vs .Primitive</a> in <cite>R Internals</cite>.
</p>
<hr>
<aname="Exception-handling"></a>
<divclass="header">
<p>
Next: <ahref="#Debugging"accesskey="n"rel="next">Debugging</a>, Previous: <ahref="#System-and-foreign-language-interfaces"accesskey="p"rel="prev">System and foreign language interfaces</a>, Up: <ahref="#Top"accesskey="u"rel="up">Top</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Exception-handling-1"></a>
<h2class="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
<tr><tdalign="left"valign="top">•<ahref="#Modes-of-parsing"accesskey="1">Modes of parsing</a>:</td><td> </td><tdalign="left"valign="top">
<tr><tdalign="left"valign="top">•<ahref="#Infix-and-prefix-operators"accesskey="2">Infix and prefix operators</a>:</td><td> </td><tdalign="left"valign="top">
<tr><tdalign="left"valign="top">•<ahref="#Flow-control-elements"accesskey="5">Flow control elements</a>:</td><td> </td><tdalign="left"valign="top">
<h4class="subsection">10.4.2 Infix and prefix operators</h4>
<p>The order of precedence (highest first) of the operators is
</p>
<divclass="example">
<preclass="example">::
$ @
^
- + <spanclass="roman">(unary)</span>
:
%<var>xyz</var>%
* /
+ - <spanclass="roman">(binary)</span>
>>= <<= == !=
!
&&&
| ||
~ <spanclass="roman">(unary and binary)</span>
-> ->>
= <spanclass="roman">(as assignment)</span>
<- <<-
</pre></div>
<p>Note that <code>:</code> precedes binary +/-, but not <code>^</code>. Hence,
<code>1:3-1</code> is <em>0 1 2</em>, but <code>1:2^3</code> is <code>1:8</code>.
</p>
<p>The exponentiation operator ‘<samp>^</samp>’ and the
<aname="index-assignment-11"></a>
left assignment plus minus operators
‘<samp><- - = <<-</samp>’ group right to left, all other operators group left to
right. That is, <code>2 ^ 2 ^ 3</code> is <em>2 ^ 8</em>, not <em>4 ^ 3</em>,
whereas <code>1 - 1 - 1</code> is <em>-1</em>, not 1.
</p>
<p>Notice that the operators <code>%%</code> and <code>%/%</code> for integer
remainder and divide have higher precedence than multiply and divide.
</p>
<p>Although it is not strictly an operator, it also needs mentioning that
the ‘<samp>=</samp>’ sign is used for tagging arguments in
function calls and
for assigning default values in function definitions.
</p>
<p>The ‘<samp>$</samp>’ sign is in some sense an operator, but does not allow
arbitrary right hand sides and is discussed under <ahref="#Index-constructions">Index constructions</a>. It has higher precedence than any of the other
operators.
</p>
<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>
<p>Parentheses are recorded as equivalent to a unary operator, with name
<code>"("</code>, even in cases where the parentheses could be inferred from
Previous: <ahref="#Flow-control-elements"accesskey="p"rel="prev">Flow control elements</a>, Up: <ahref="#Expressions"accesskey="u"rel="up">Expressions</a> [<ahref="#SEC_Contents"title="Table of contents"rel="contents">Contents</a>][<ahref="#Function-and-Variable-Index"title="Index"rel="index">Index</a>]</p>
</div>
<aname="Function-definitions-1"></a>
<h4class="subsection">10.4.6 Function definitions</h4>
<tr><td></td><tdvalign="top"><ahref="#index-_002eC"><code>.C</code></a>:</td><td> </td><tdvalign="top"><ahref="#Foreign-language-interfaces">Foreign language interfaces</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-_002eCall"><code>.Call</code></a>:</td><td> </td><tdvalign="top"><ahref="#Foreign-language-interfaces">Foreign language interfaces</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-_002eExternal"><code>.External</code></a>:</td><td> </td><tdvalign="top"><ahref="#Foreign-language-interfaces">Foreign language interfaces</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-_002eFortran"><code>.Fortran</code></a>:</td><td> </td><tdvalign="top"><ahref="#Foreign-language-interfaces">Foreign language interfaces</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-_002eInternal-1"><code>.Internal</code></a>:</td><td> </td><tdvalign="top"><ahref="#g_t_002eInternal-and-_002ePrimitive">.Internal and .Primitive</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-_002ePrimitive-1"><code>.Primitive</code></a>:</td><td> </td><tdvalign="top"><ahref="#g_t_002eInternal-and-_002ePrimitive">.Internal and .Primitive</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-basename"><code>basename</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-body-1"><code>body</code></a>:</td><td> </td><tdvalign="top"><ahref="#Manipulation-of-functions">Manipulation of functions</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-body_003c_002d"><code>body<-</code></a>:</td><td> </td><tdvalign="top"><ahref="#Manipulation-of-functions">Manipulation of functions</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-dirname"><code>dirname</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-do_002ecall"><code>do.call</code></a>:</td><td> </td><tdvalign="top"><ahref="#Manipulation-of-function-calls">Manipulation of function calls</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-environment-21"><code>environment</code></a>:</td><td> </td><tdvalign="top"><ahref="#Manipulation-of-functions">Manipulation of functions</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-environment_003c_002d"><code>environment<-</code></a>:</td><td> </td><tdvalign="top"><ahref="#Manipulation-of-functions">Manipulation of functions</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-eval"><code>eval</code></a>:</td><td> </td><tdvalign="top"><ahref="#More-on-evaluation">More on evaluation</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-file_002eaccess"><code>file.access</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-file_002eappend"><code>file.append</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-file_002echoose"><code>file.choose</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-file_002ecopy"><code>file.copy</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-file_002ecreate"><code>file.create</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-file_002eexists"><code>file.exists</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-file_002einfo"><code>file.info</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-file_002epath"><code>file.path</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-file_002eremove"><code>file.remove</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-file_002erename"><code>file.rename</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-file_002eshow"><code>file.show</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-formals-1"><code>formals</code></a>:</td><td> </td><tdvalign="top"><ahref="#Manipulation-of-functions">Manipulation of functions</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-formals_003c_002d"><code>formals<-</code></a>:</td><td> </td><tdvalign="top"><ahref="#Manipulation-of-functions">Manipulation of functions</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-match_002ecall-1"><code>match.call</code></a>:</td><td> </td><tdvalign="top"><ahref="#Manipulation-of-function-calls">Manipulation of function calls</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-NA-1"><code>NA</code></a>:</td><td> </td><tdvalign="top"><ahref="#Indexing-by-vectors">Indexing by vectors</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-path_002eexpand"><code>path.expand</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-proc_002etime"><code>proc.time</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-Sys_002egetenv"><code>Sys.getenv</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-Sys_002egetlocale"><code>Sys.getlocale</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-Sys_002elocaleconv"><code>Sys.localeconv</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-Sys_002eputenv"><code>Sys.putenv</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-Sys_002eputlocale"><code>Sys.putlocale</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-Sys_002etime"><code>Sys.time</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-Sys_002etimezone"><code>Sys.timezone</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-system"><code>system</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-system_002etime"><code>system.time</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-unlink"><code>unlink</code></a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-_002eInternal">.Internal</a>:</td><td> </td><tdvalign="top"><ahref="#Builtin-objects-and-special-forms">Builtin objects and special forms</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-_002ePrimitive">.Primitive</a>:</td><td> </td><tdvalign="top"><ahref="#Builtin-objects-and-special-forms">Builtin objects and special forms</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-argument-1">argument</a>:</td><td> </td><tdvalign="top"><ahref="#Syntax-and-examples">Syntax and examples</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-assignment-9">assignment</a>:</td><td> </td><tdvalign="top"><ahref="#More-on-evaluation">More on evaluation</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-assignment-10">assignment</a>:</td><td> </td><tdvalign="top"><ahref="#Manipulation-of-function-calls">Manipulation of function calls</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-assignment-11">assignment</a>:</td><td> </td><tdvalign="top"><ahref="#Infix-and-prefix-operators">Infix and prefix operators</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-assignment-12">assignment</a>:</td><td> </td><tdvalign="top"><ahref="#Infix-and-prefix-operators">Infix and prefix operators</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-environment-15">environment</a>:</td><td> </td><tdvalign="top"><ahref="#More-on-evaluation">More on evaluation</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-environment-16">environment</a>:</td><td> </td><tdvalign="top"><ahref="#Manipulation-of-functions">Manipulation of functions</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-environment-17">environment</a>:</td><td> </td><tdvalign="top"><ahref="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-evaluation-6">evaluation</a>:</td><td> </td><tdvalign="top"><ahref="#More-on-evaluation">More on evaluation</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-evaluation-7">evaluation</a>:</td><td> </td><tdvalign="top"><ahref="#Manipulation-of-function-calls">Manipulation of function calls</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-function-3">function</a>:</td><td> </td><tdvalign="top"><ahref="#Builtin-objects-and-special-forms">Builtin objects and special forms</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-function-4">function</a>:</td><td> </td><tdvalign="top"><ahref="#Builtin-objects-and-special-forms">Builtin objects and special forms</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-function-12">function</a>:</td><td> </td><tdvalign="top"><ahref="#Syntax-and-examples">Syntax and examples</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-function-13">function</a>:</td><td> </td><tdvalign="top"><ahref="#Syntax-and-examples">Syntax and examples</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-function-26">function</a>:</td><td> </td><tdvalign="top"><ahref="#Manipulation-of-function-calls">Manipulation of function calls</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-function-27">function</a>:</td><td> </td><tdvalign="top"><ahref="#Manipulation-of-functions">Manipulation of functions</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-function-28">function</a>:</td><td> </td><tdvalign="top"><ahref="#Manipulation-of-functions">Manipulation of functions</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-function_002c-anonymous">function, anonymous</a>:</td><td> </td><tdvalign="top"><ahref="#Syntax-and-examples">Syntax and examples</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-index-3">index</a>:</td><td> </td><tdvalign="top"><ahref="#Indexing-by-vectors">Indexing by vectors</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-index-4">index</a>:</td><td> </td><tdvalign="top"><ahref="#Indexing-matrices-and-arrays">Indexing matrices and arrays</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-index-5">index</a>:</td><td> </td><tdvalign="top"><ahref="#Indexing-matrices-and-arrays">Indexing matrices and arrays</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-name-3">name</a>:</td><td> </td><tdvalign="top"><ahref="#Propagation-of-names">Propagation of names</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-name-4">name</a>:</td><td> </td><tdvalign="top"><ahref="#Scope-of-variables">Scope of variables</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-name-10">name</a>:</td><td> </td><tdvalign="top"><ahref="#Direct-manipulation-of-language-objects">Direct manipulation of language objects</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-parsing-2">parsing</a>:</td><td> </td><tdvalign="top"><ahref="#Evaluation-of-expressions">Evaluation of expressions</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-parsing-3">parsing</a>:</td><td> </td><tdvalign="top"><ahref="#Computing-on-the-language">Computing on the language</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-parsing-4">parsing</a>:</td><td> </td><tdvalign="top"><ahref="#Direct-manipulation-of-language-objects">Direct manipulation of language objects</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-partial-matching">partial matching</a>:</td><td> </td><tdvalign="top"><ahref="#Indexing-by-vectors">Indexing by vectors</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-scope">scope</a>:</td><td> </td><tdvalign="top"><ahref="#Scope-of-variables">Scope of variables</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-scope-5">scope</a>:</td><td> </td><tdvalign="top"><ahref="#More-on-evaluation">More on evaluation</a></td></tr>
<tr><td></td><tdvalign="top"><ahref="#index-symbol-5">symbol</a>:</td><td> </td><tdvalign="top"><ahref="#Manipulation-of-function-calls">Manipulation of function calls</a></td></tr>