0byt3m1n1
Path:
C:
/
Program Files
/
R
/
R-4.4.1
/
doc
/
manual
/
[
Home
]
File: R-intro.html
<!DOCTYPE html> <html> <!-- Created by GNU Texinfo 7.1, https://www.gnu.org/software/texinfo/ --> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <!-- This manual is for R, version 4.4.1 (2024-06-14). Copyright © 1990 W. N. Venables Copyright © 1992 W. N. Venables & D. M. Smith Copyright © 1997 R. Gentleman & R. Ihaka Copyright © 1997, 1998 M. Maechler Copyright © 1999-2024 R Core Team Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the R Core Team. --> <title>An Introduction to R</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="An Introduction to R"> <meta name="keywords" content="An Introduction to R"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="texi2any"> <meta name="viewport" content="width=device-width,initial-scale=1"> <link href="#Top" rel="start" title="Top"> <link href="#Function-and-variable-index" rel="index" title="Function and variable index"> <link href="#SEC_Contents" rel="contents" title="Table of Contents"> <link href="#Preface" rel="next" title="Preface"> <style type="text/css"> <!-- a.copiable-link {visibility: hidden; text-decoration: none; line-height: 0em} a.summary-letter-printindex {text-decoration: none} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} kbd.kbd {font-style: oblique} kbd.key {font-style: normal} pre.display-preformatted {font-family: inherit} span.r {font-family: initial; font-weight: normal; font-style: normal} span:hover a.copiable-link {visibility: visible} td.printindex-index-entry {vertical-align: top} td.printindex-index-section {vertical-align: top; padding-left: 1em} th.entries-header-printindex {text-align:left} th.sections-header-printindex {text-align:left; padding-left: 1em} ul.mark-bullet {list-style-type: disc} ul.toc-numbered-mark {list-style: none} body { margin-left: 5%; margin-right: 5%; } h1 { background: white; color: rgb(25%, 25%, 25%); font-family: monospace; font-size: xx-large; text-align: center; } h2 { background: white; color: rgb(40%, 40%, 40%); font-family: monospace; font-size: x-large; text-align: center; } h3 { background: white; color: rgb(40%, 40%, 40%); font-family: monospace; font-size: large; } h4 { background: white; color: rgb(40%, 40%, 40%); font-family: monospace; } span.samp { font-family: monospace; } span.command { font-family: monospace; } span.option { font-family: monospace; } span.file { font-family: monospace; } span.env { font-family: monospace; } ul { margin-top: 0.25ex; margin-bottom: 0.25ex; } li { margin-top: 0.25ex; margin-bottom: 0.25ex; } p { margin-top: 0.6ex; margin-bottom: 1.2ex; } /* hide top navigation bar in Texinfo >= 6.8 output */ #Top > .header, #Top > .nav-panel { display: none } --> </style> </head> <body lang="en"> <div class="top-level-extent" id="Top"> <div class="nav-panel"> <p> Next: <a href="#Preface" accesskey="n" rel="next">Preface</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h1 class="top" id="An-Introduction-to-R"><span>An Introduction to R<a class="copiable-link" href="#An-Introduction-to-R"> ¶</a></span></h1> <p>This is an introduction to R (“GNU S”), a language and environment for statistical computing and graphics. R is similar to the award-winning<a class="footnote" id="DOCF1" href="#FOOT1"><sup>1</sup></a> S system, which was developed at Bell Laboratories by John Chambers et al. It provides a wide variety of statistical and graphical techniques (linear and nonlinear modelling, statistical tests, time series analysis, classification, clustering, ...). </p> <p>This manual provides information on data types, programming elements, statistical modelling and graphics. </p> <p>This manual is for R, version 4.4.1 (2024-06-14). </p> <p>Copyright © 1990 W. N. Venables<br> Copyright © 1992 W. N. Venables & D. M. Smith<br> Copyright © 1997 R. Gentleman & R. Ihaka<br> Copyright © 1997, 1998 M. Maechler<br> Copyright © 1999–2024 R Core Team </p> <blockquote class="quotation"> <p>Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. </p> <p>Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. </p> <p>Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the R Core Team. </p></blockquote> <div class="element-contents" id="SEC_Contents"> <h2 class="contents-heading">Table of Contents</h2> <div class="contents"> <ul class="toc-numbered-mark"> <li><a id="toc-Preface-1" href="#Preface">Preface</a></li> <li><a id="toc-Introduction-and-preliminaries-1" href="#Introduction-and-preliminaries">1 Introduction and preliminaries</a> <ul class="toc-numbered-mark"> <li><a id="toc-The-R-environment-1" href="#The-R-environment">1.1 The R environment</a></li> <li><a id="toc-Related-software-and-documentation-1" href="#Related-software-and-documentation">1.2 Related software and documentation</a></li> <li><a id="toc-R-and-statistics-1" href="#R-and-statistics">1.3 R and statistics</a></li> <li><a id="toc-R-and-the-window-system-1" href="#R-and-the-window-system">1.4 R and the window system</a></li> <li><a id="toc-Using-R-interactively-1" href="#Using-R-interactively">1.5 Using R interactively</a></li> <li><a id="toc-An-introductory-session" href="#An-introductory-session">1.6 An introductory session</a></li> <li><a id="toc-Getting-help-with-functions-and-features" href="#Getting-help">1.7 Getting help with functions and features</a></li> <li><a id="toc-R-commands_002c-case-sensitivity_002c-etc_002e" href="#R-commands_003b-case-sensitivity-etc">1.8 R commands, case sensitivity, etc.</a></li> <li><a id="toc-Recall-and-correction-of-previous-commands-1" href="#Recall-and-correction-of-previous-commands">1.9 Recall and correction of previous commands</a></li> <li><a id="toc-Executing-commands-from-or-diverting-output-to-a-file-1" href="#Executing-commands-from-or-diverting-output-to-a-file">1.10 Executing commands from or diverting output to a file</a></li> <li><a id="toc-Data-permanency-and-removing-objects-1" href="#Data-permanency-and-removing-objects">1.11 Data permanency and removing objects</a></li> </ul></li> <li><a id="toc-Simple-manipulations_003b-numbers-and-vectors" href="#Simple-manipulations-numbers-and-vectors">2 Simple manipulations; numbers and vectors</a> <ul class="toc-numbered-mark"> <li><a id="toc-Vectors-and-assignment-1" href="#Vectors-and-assignment">2.1 Vectors and assignment</a></li> <li><a id="toc-Vector-arithmetic-1" href="#Vector-arithmetic">2.2 Vector arithmetic</a></li> <li><a id="toc-Generating-regular-sequences-1" href="#Generating-regular-sequences">2.3 Generating regular sequences</a></li> <li><a id="toc-Logical-vectors-1" href="#Logical-vectors">2.4 Logical vectors</a></li> <li><a id="toc-Missing-values-1" href="#Missing-values">2.5 Missing values</a></li> <li><a id="toc-Character-vectors-1" href="#Character-vectors">2.6 Character vectors</a></li> <li><a id="toc-Index-vectors_003b-selecting-and-modifying-subsets-of-a-data-set" href="#Index-vectors">2.7 Index vectors; selecting and modifying subsets of a data set</a></li> <li><a id="toc-Other-types-of-objects-1" href="#Other-types-of-objects">2.8 Other types of objects</a></li> </ul></li> <li><a id="toc-Objects_002c-their-modes-and-attributes" href="#Objects">3 Objects, their modes and attributes</a> <ul class="toc-numbered-mark"> <li><a id="toc-Intrinsic-attributes_003a-mode-and-length" href="#The-intrinsic-attributes-mode-and-length">3.1 Intrinsic attributes: mode and length</a></li> <li><a id="toc-Changing-the-length-of-an-object-1" href="#Changing-the-length-of-an-object">3.2 Changing the length of an object</a></li> <li><a id="toc-Getting-and-setting-attributes-1" href="#Getting-and-setting-attributes">3.3 Getting and setting attributes</a></li> <li><a id="toc-The-class-of-an-object-1" href="#The-class-of-an-object">3.4 The class of an object</a></li> </ul></li> <li><a id="toc-Ordered-and-unordered-factors" href="#Factors">4 Ordered and unordered factors</a> <ul class="toc-numbered-mark"> <li><a id="toc-A-specific-example" href="#A-specific-example">4.1 A specific example</a></li> <li><a id="toc-The-function-tapply_0028_0029-and-ragged-arrays-1" href="#The-function-tapply_0028_0029-and-ragged-arrays">4.2 The function <code class="code">tapply()</code> and ragged arrays</a></li> <li><a id="toc-Ordered-factors-1" href="#Ordered-factors">4.3 Ordered factors</a></li> </ul></li> <li><a id="toc-Arrays-and-matrices-1" href="#Arrays-and-matrices">5 Arrays and matrices</a> <ul class="toc-numbered-mark"> <li><a id="toc-Arrays-1" href="#Arrays">5.1 Arrays</a></li> <li><a id="toc-Array-indexing_002e-Subsections-of-an-array" href="#Array-indexing">5.2 Array indexing. Subsections of an array</a></li> <li><a id="toc-Index-matrices-1" href="#Index-matrices">5.3 Index matrices</a></li> <li><a id="toc-The-array_0028_0029-function-1" href="#The-array_0028_0029-function">5.4 The <code class="code">array()</code> function</a> <ul class="toc-numbered-mark"> <li><a id="toc-Mixed-vector-and-array-arithmetic_002e-The-recycling-rule" href="#The-recycling-rule">5.4.1 Mixed vector and array arithmetic. The recycling rule</a></li> </ul></li> <li><a id="toc-The-outer-product-of-two-arrays-1" href="#The-outer-product-of-two-arrays">5.5 The outer product of two arrays</a></li> <li><a id="toc-Generalized-transpose-of-an-array-1" href="#Generalized-transpose-of-an-array">5.6 Generalized transpose of an array</a></li> <li><a id="toc-Matrix-facilities-1" href="#Matrix-facilities">5.7 Matrix facilities</a> <ul class="toc-numbered-mark"> <li><a id="toc-Matrix-multiplication" href="#Multiplication">5.7.1 Matrix multiplication</a></li> <li><a id="toc-Linear-equations-and-inversion-1" href="#Linear-equations-and-inversion">5.7.2 Linear equations and inversion</a></li> <li><a id="toc-Eigenvalues-and-eigenvectors-1" href="#Eigenvalues-and-eigenvectors">5.7.3 Eigenvalues and eigenvectors</a></li> <li><a id="toc-Singular-value-decomposition-and-determinants-1" href="#Singular-value-decomposition-and-determinants">5.7.4 Singular value decomposition and determinants</a></li> <li><a id="toc-Least-squares-fitting-and-the-QR-decomposition-1" href="#Least-squares-fitting-and-the-QR-decomposition">5.7.5 Least squares fitting and the QR decomposition</a></li> </ul></li> <li><a id="toc-Forming-partitioned-matrices_002c-cbind_0028_0029-and-rbind_0028_0029" href="#Forming-partitioned-matrices">5.8 Forming partitioned matrices, <code class="code">cbind()</code> and <code class="code">rbind()</code></a></li> <li><a id="toc-The-concatenation-function_002c-c_0028_0029_002c-with-arrays" href="#The-concatenation-function-c_0028_0029-with-arrays">5.9 The concatenation function, <code class="code">c()</code>, with arrays</a></li> <li><a id="toc-Frequency-tables-from-factors-1" href="#Frequency-tables-from-factors">5.10 Frequency tables from factors</a></li> </ul></li> <li><a id="toc-Lists-and-data-frames-1" href="#Lists-and-data-frames">6 Lists and data frames</a> <ul class="toc-numbered-mark"> <li><a id="toc-Lists-1" href="#Lists">6.1 Lists</a></li> <li><a id="toc-Constructing-and-modifying-lists-1" href="#Constructing-and-modifying-lists">6.2 Constructing and modifying lists</a> <ul class="toc-numbered-mark"> <li><a id="toc-Concatenating-lists-1" href="#Concatenating-lists">6.2.1 Concatenating lists</a></li> </ul></li> <li><a id="toc-Data-frames-1" href="#Data-frames">6.3 Data frames</a> <ul class="toc-numbered-mark"> <li><a id="toc-Making-data-frames-1" href="#Making-data-frames">6.3.1 Making data frames</a></li> <li><a id="toc-attach_0028_0029-and-detach_0028_0029-1" href="#attach_0028_0029-and-detach_0028_0029">6.3.2 <code class="code">attach()</code> and <code class="code">detach()</code></a></li> <li><a id="toc-Working-with-data-frames-1" href="#Working-with-data-frames">6.3.3 Working with data frames</a></li> <li><a id="toc-Attaching-arbitrary-lists-1" href="#Attaching-arbitrary-lists">6.3.4 Attaching arbitrary lists</a></li> <li><a id="toc-Managing-the-search-path-1" href="#Managing-the-search-path">6.3.5 Managing the search path</a></li> </ul></li> </ul></li> <li><a id="toc-Reading-data-from-files-1" href="#Reading-data-from-files">7 Reading data from files</a> <ul class="toc-numbered-mark"> <li><a id="toc-The-read_002etable_0028_0029-function-1" href="#The-read_002etable_0028_0029-function">7.1 The <code class="code">read.table()</code> function</a></li> <li><a id="toc-The-scan_0028_0029-function-1" href="#The-scan_0028_0029-function">7.2 The <code class="code">scan()</code> function</a></li> <li><a id="toc-Accessing-builtin-datasets-1" href="#Accessing-builtin-datasets">7.3 Accessing builtin datasets</a> <ul class="toc-numbered-mark"> <li><a id="toc-Loading-data-from-other-R-packages" href="#Loading-data-from-other-R-packages">7.3.1 Loading data from other R packages</a></li> </ul></li> <li><a id="toc-Editing-data-1" href="#Editing-data">7.4 Editing data</a></li> </ul></li> <li><a id="toc-Probability-distributions-1" href="#Probability-distributions">8 Probability distributions</a> <ul class="toc-numbered-mark"> <li><a id="toc-R-as-a-set-of-statistical-tables-1" href="#R-as-a-set-of-statistical-tables">8.1 R as a set of statistical tables</a></li> <li><a id="toc-Examining-the-distribution-of-a-set-of-data-1" href="#Examining-the-distribution-of-a-set-of-data">8.2 Examining the distribution of a set of data</a></li> <li><a id="toc-One_002d-and-two_002dsample-tests-1" href="#One_002d-and-two_002dsample-tests">8.3 One- and two-sample tests</a></li> </ul></li> <li><a id="toc-Grouping_002c-loops-and-conditional-execution" href="#Loops-and-conditional-execution">9 Grouping, loops and conditional execution</a> <ul class="toc-numbered-mark"> <li><a id="toc-Grouped-expressions-1" href="#Grouped-expressions">9.1 Grouped expressions</a></li> <li><a id="toc-Control-statements-1" href="#Control-statements">9.2 Control statements</a> <ul class="toc-numbered-mark"> <li><a id="toc-Conditional-execution_003a-if-statements" href="#Conditional-execution">9.2.1 Conditional execution: <code class="code">if</code> statements</a></li> <li><a id="toc-Repetitive-execution_003a-for-loops_002c-repeat-and-while" href="#Repetitive-execution">9.2.2 Repetitive execution: <code class="code">for</code> loops, <code class="code">repeat</code> and <code class="code">while</code></a></li> </ul></li> </ul></li> <li><a id="toc-Writing-your-own-functions-1" href="#Writing-your-own-functions">10 Writing your own functions</a> <ul class="toc-numbered-mark"> <li><a id="toc-Simple-examples-1" href="#Simple-examples">10.1 Simple examples</a></li> <li><a id="toc-Defining-new-binary-operators-1" href="#Defining-new-binary-operators">10.2 Defining new binary operators</a></li> <li><a id="toc-Named-arguments-and-defaults-1" href="#Named-arguments-and-defaults">10.3 Named arguments and defaults</a></li> <li><a id="toc-The-_2026-argument" href="#The-three-dots-argument">10.4 The ‘<samp class="samp">…</samp>’ argument</a></li> <li><a id="toc-Assignments-within-functions" href="#Assignment-within-functions">10.5 Assignments within functions</a></li> <li><a id="toc-More-advanced-examples-1" href="#More-advanced-examples">10.6 More advanced examples</a> <ul class="toc-numbered-mark"> <li><a id="toc-Efficiency-factors-in-block-designs-1" href="#Efficiency-factors-in-block-designs">10.6.1 Efficiency factors in block designs</a></li> <li><a id="toc-Dropping-all-names-in-a-printed-array-1" href="#Dropping-all-names-in-a-printed-array">10.6.2 Dropping all names in a printed array</a></li> <li><a id="toc-Recursive-numerical-integration-1" href="#Recursive-numerical-integration">10.6.3 Recursive numerical integration</a></li> </ul></li> <li><a id="toc-Scope-1" href="#Scope">10.7 Scope</a></li> <li><a id="toc-Customizing-the-environment-1" href="#Customizing-the-environment">10.8 Customizing the environment</a></li> <li><a id="toc-Classes_002c-generic-functions-and-object-orientation" href="#Object-orientation">10.9 Classes, generic functions and object orientation</a></li> </ul></li> <li><a id="toc-Statistical-models-in-R-1" href="#Statistical-models-in-R">11 Statistical models in R</a> <ul class="toc-numbered-mark"> <li><a id="toc-Defining-statistical-models_003b-formulae" href="#Formulae-for-statistical-models">11.1 Defining statistical models; formulae</a> <ul class="toc-numbered-mark"> <li><a id="toc-Contrasts-1" href="#Contrasts">11.1.1 Contrasts</a></li> </ul></li> <li><a id="toc-Linear-models-1" href="#Linear-models">11.2 Linear models</a></li> <li><a id="toc-Generic-functions-for-extracting-model-information-1" href="#Generic-functions-for-extracting-model-information">11.3 Generic functions for extracting model information</a></li> <li><a id="toc-Analysis-of-variance-and-model-comparison-1" href="#Analysis-of-variance-and-model-comparison">11.4 Analysis of variance and model comparison</a> <ul class="toc-numbered-mark"> <li><a id="toc-ANOVA-tables-1" href="#ANOVA-tables">11.4.1 ANOVA tables</a></li> </ul></li> <li><a id="toc-Updating-fitted-models-1" href="#Updating-fitted-models">11.5 Updating fitted models</a></li> <li><a id="toc-Generalized-linear-models-1" href="#Generalized-linear-models">11.6 Generalized linear models</a> <ul class="toc-numbered-mark"> <li><a id="toc-Families-1" href="#Families">11.6.1 Families</a></li> <li><a id="toc-The-glm_0028_0029-function-1" href="#The-glm_0028_0029-function">11.6.2 The <code class="code">glm()</code> function</a></li> </ul></li> <li><a id="toc-Nonlinear-least-squares-and-maximum-likelihood-models-1" href="#Nonlinear-least-squares-and-maximum-likelihood-models">11.7 Nonlinear least squares and maximum likelihood models</a> <ul class="toc-numbered-mark"> <li><a id="toc-Least-squares-1" href="#Least-squares">11.7.1 Least squares</a></li> <li><a id="toc-Maximum-likelihood-1" href="#Maximum-likelihood">11.7.2 Maximum likelihood</a></li> </ul></li> <li><a id="toc-Some-non_002dstandard-models-1" href="#Some-non_002dstandard-models">11.8 Some non-standard models</a></li> </ul></li> <li><a id="toc-Graphical-procedures" href="#Graphics">12 Graphical procedures</a> <ul class="toc-numbered-mark"> <li><a id="toc-High_002dlevel-plotting-commands-1" href="#High_002dlevel-plotting-commands">12.1 High-level plotting commands</a> <ul class="toc-numbered-mark"> <li><a id="toc-The-plot_0028_0029-function-1" href="#The-plot_0028_0029-function">12.1.1 The <code class="code">plot()</code> function</a></li> <li><a id="toc-Displaying-multivariate-data-1" href="#Displaying-multivariate-data">12.1.2 Displaying multivariate data</a></li> <li><a id="toc-Display-graphics-1" href="#Display-graphics">12.1.3 Display graphics</a></li> <li><a id="toc-Arguments-to-high_002dlevel-plotting-functions-1" href="#Arguments-to-high_002dlevel-plotting-functions">12.1.4 Arguments to high-level plotting functions</a></li> </ul></li> <li><a id="toc-Low_002dlevel-plotting-commands-1" href="#Low_002dlevel-plotting-commands">12.2 Low-level plotting commands</a> <ul class="toc-numbered-mark"> <li><a id="toc-Mathematical-annotation-1" href="#Mathematical-annotation">12.2.1 Mathematical annotation</a></li> <li><a id="toc-Hershey-vector-fonts-1" href="#Hershey-vector-fonts">12.2.2 Hershey vector fonts</a></li> </ul></li> <li><a id="toc-Interacting-with-graphics-1" href="#Interacting-with-graphics">12.3 Interacting with graphics</a></li> <li><a id="toc-Using-graphics-parameters-1" href="#Using-graphics-parameters">12.4 Using graphics parameters</a> <ul class="toc-numbered-mark"> <li><a id="toc-Permanent-changes_003a-The-par_0028_0029-function" href="#The-par_0028_0029-function">12.4.1 Permanent changes: The <code class="code">par()</code> function</a></li> <li><a id="toc-Temporary-changes_003a-Arguments-to-graphics-functions" href="#Arguments-to-graphics-functions">12.4.2 Temporary changes: Arguments to graphics functions</a></li> </ul></li> <li><a id="toc-Graphics-parameters-list" href="#Graphics-parameters">12.5 Graphics parameters list</a> <ul class="toc-numbered-mark"> <li><a id="toc-Graphical-elements-1" href="#Graphical-elements">12.5.1 Graphical elements</a></li> <li><a id="toc-Axes-and-tick-marks-1" href="#Axes-and-tick-marks">12.5.2 Axes and tick marks</a></li> <li><a id="toc-Figure-margins-1" href="#Figure-margins">12.5.3 Figure margins</a></li> <li><a id="toc-Multiple-figure-environment-1" href="#Multiple-figure-environment">12.5.4 Multiple figure environment</a></li> </ul></li> <li><a id="toc-Device-drivers-1" href="#Device-drivers">12.6 Device drivers</a> <ul class="toc-numbered-mark"> <li><a id="toc-PostScript-diagrams-for-typeset-documents-1" href="#PostScript-diagrams-for-typeset-documents">12.6.1 PostScript diagrams for typeset documents</a></li> <li><a id="toc-Multiple-graphics-devices-1" href="#Multiple-graphics-devices">12.6.2 Multiple graphics devices</a></li> </ul></li> <li><a id="toc-Dynamic-graphics-1" href="#Dynamic-graphics">12.7 Dynamic graphics</a></li> </ul></li> <li><a id="toc-Packages-1" href="#Packages">13 Packages</a> <ul class="toc-numbered-mark"> <li><a id="toc-Standard-packages-1" href="#Standard-packages">13.1 Standard packages</a></li> <li><a id="toc-Contributed-packages-and-CRAN-1" href="#Contributed-packages-and-CRAN">13.2 Contributed packages and <abbr class="acronym">CRAN</abbr></a></li> <li><a id="toc-Namespaces-1" href="#Namespaces">13.3 Namespaces</a></li> </ul></li> <li><a id="toc-OS-facilities-1" href="#OS-facilities">14 OS facilities</a> <ul class="toc-numbered-mark"> <li><a id="toc-Files-and-directories-1" href="#Files-and-directories">14.1 Files and directories</a></li> <li><a id="toc-Filepaths-1" href="#Filepaths">14.2 Filepaths</a></li> <li><a id="toc-System-commands-1" href="#System-commands">14.3 System commands</a></li> <li><a id="toc-Compression-and-Archives-1" href="#Compression-and-Archives">14.4 Compression and Archives</a></li> </ul></li> <li><a id="toc-A-sample-session-1" href="#A-sample-session">Appendix A A sample session</a></li> <li><a id="toc-Invoking-R-1" href="#Invoking-R">Appendix B Invoking R</a> <ul class="toc-numbered-mark"> <li><a id="toc-Invoking-R-from-the-command-line-1" href="#Invoking-R-from-the-command-line">B.1 Invoking R from the command line</a></li> <li><a id="toc-Invoking-R-under-Windows-1" href="#Invoking-R-under-Windows">B.2 Invoking R under Windows</a></li> <li><a id="toc-Invoking-R-under-macOS-1" href="#Invoking-R-under-macOS">B.3 Invoking R under macOS</a></li> <li><a id="toc-Scripting-with-R-1" href="#Scripting-with-R">B.4 Scripting with R</a></li> </ul></li> <li><a id="toc-The-command_002dline-editor-1" href="#The-command_002dline-editor">Appendix C The command-line editor</a> <ul class="toc-numbered-mark"> <li><a id="toc-Preliminaries" href="#Preliminaries">C.1 Preliminaries</a></li> <li><a id="toc-Editing-actions" href="#Editing-actions">C.2 Editing actions</a></li> <li><a id="toc-Command_002dline-editor-summary" href="#Command_002dline-editor-summary">C.3 Command-line editor summary</a></li> </ul></li> <li><a id="toc-Function-and-variable-index-1" href="#Function-and-variable-index" rel="index">Appendix D Function and variable index</a></li> <li><a id="toc-Concept-index-1" href="#Concept-index" rel="index">Appendix E Concept index</a></li> <li><a id="toc-References-1" href="#References">Appendix F References</a></li> </ul> </div> </div> <hr> <div class="unnumbered-level-extent" id="Preface"> <div class="nav-panel"> <p> Next: <a href="#Introduction-and-preliminaries" accesskey="n" rel="next">Introduction and preliminaries</a>, Previous: <a href="#Top" accesskey="p" rel="prev">An Introduction to R</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="unnumbered" id="Preface-1"><span>Preface<a class="copiable-link" href="#Preface-1"> ¶</a></span></h2> <p>This introduction to R is derived from an original set of notes describing the S and <small class="sc">S-PLUS</small> environments written in 1990–2 by Bill Venables and David M. Smith when at the University of Adelaide. We have made a number of small changes to reflect differences between the R and S programs, and expanded some of the material. </p> <p>We would like to extend warm thanks to Bill Venables (and David Smith) for granting permission to distribute this modified version of the notes in this way, and for being a supporter of R from way back. </p> <p>Comments and corrections are always welcome. Please address email correspondence to <a class="email" href="mailto:R-help@R-project.org">R-help@R-project.org</a>. </p> <h4 class="subheading" id="Suggestions-to-the-reader"><span>Suggestions to the reader<a class="copiable-link" href="#Suggestions-to-the-reader"> ¶</a></span></h4> <p>Most R novices will start with the introductory session in Appendix A. This should give some familiarity with the style of R sessions and more importantly some instant feedback on what actually happens. </p> <p>Many users will come to R mainly for its graphical facilities. See <a class="xref" href="#Graphics">Graphical procedures</a>, which can be read at almost any time and need not wait until all the preceding sections have been digested. </p> <hr> </div> <div class="chapter-level-extent" id="Introduction-and-preliminaries"> <div class="nav-panel"> <p> Next: <a href="#Simple-manipulations-numbers-and-vectors" accesskey="n" rel="next">Simple manipulations; numbers and vectors</a>, Previous: <a href="#Preface" accesskey="p" rel="prev">Preface</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="chapter" id="Introduction-and-preliminaries-1"><span>1 Introduction and preliminaries<a class="copiable-link" href="#Introduction-and-preliminaries-1"> ¶</a></span></h2> <ul class="mini-toc"> <li><a href="#The-R-environment" accesskey="1">The R environment</a></li> <li><a href="#Related-software-and-documentation" accesskey="2">Related software and documentation</a></li> <li><a href="#R-and-statistics" accesskey="3">R and statistics</a></li> <li><a href="#R-and-the-window-system" accesskey="4">R and the window system</a></li> <li><a href="#Using-R-interactively" accesskey="5">Using R interactively</a></li> <li><a href="#An-introductory-session" accesskey="6">An introductory session</a></li> <li><a href="#Getting-help" accesskey="7">Getting help with functions and features</a></li> <li><a href="#R-commands_003b-case-sensitivity-etc" accesskey="8">R commands, case sensitivity, etc.</a></li> <li><a href="#Recall-and-correction-of-previous-commands" accesskey="9">Recall and correction of previous commands</a></li> <li><a href="#Executing-commands-from-or-diverting-output-to-a-file">Executing commands from or diverting output to a file</a></li> <li><a href="#Data-permanency-and-removing-objects">Data permanency and removing objects</a></li> </ul> <hr> <div class="section-level-extent" id="The-R-environment"> <div class="nav-panel"> <p> Next: <a href="#Related-software-and-documentation" accesskey="n" rel="next">Related software and documentation</a>, Previous: <a href="#Introduction-and-preliminaries" accesskey="p" rel="prev">Introduction and preliminaries</a>, Up: <a href="#Introduction-and-preliminaries" accesskey="u" rel="up">Introduction and preliminaries</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="The-R-environment-1"><span>1.1 The R environment<a class="copiable-link" href="#The-R-environment-1"> ¶</a></span></h3> <p>R is an integrated suite of software facilities for data manipulation, calculation and graphical display. Among other things it has </p> <ul class="itemize mark-bullet"> <li>an effective data handling and storage facility, </li><li>a suite of operators for calculations on arrays, in particular matrices, </li><li>a large, coherent, integrated collection of intermediate tools for data analysis, </li><li>graphical facilities for data analysis and display either directly at the computer or on hardcopy, and </li><li>a well developed, simple and effective programming language (called ‘S’) which includes conditionals, loops, user defined recursive functions and input and output facilities. (Indeed most of the system supplied functions are themselves written in the S language.) </li></ul> <p>The term “environment” is intended to characterize it as a fully planned and coherent system, rather than an incremental accretion of very specific and inflexible tools, as is frequently the case with other data analysis software. </p> <p>R is very much a vehicle for newly developing methods of interactive data analysis. It has developed rapidly, and has been extended by a large collection of <em class="emph">packages</em>. However, most programs written in R are essentially ephemeral, written for a single piece of data analysis. </p> <hr> </div> <div class="section-level-extent" id="Related-software-and-documentation"> <div class="nav-panel"> <p> Next: <a href="#R-and-statistics" accesskey="n" rel="next">R and statistics</a>, Previous: <a href="#The-R-environment" accesskey="p" rel="prev">The R environment</a>, Up: <a href="#Introduction-and-preliminaries" accesskey="u" rel="up">Introduction and preliminaries</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Related-software-and-documentation-1"><span>1.2 Related software and documentation<a class="copiable-link" href="#Related-software-and-documentation-1"> ¶</a></span></h3> <p>R can be regarded as an implementation of the S language which was developed at Bell Laboratories by Rick Becker, John Chambers and Allan Wilks, and also forms the basis of the <small class="sc">S-PLUS</small> systems. </p> <p>The evolution of the S language is characterized by four books by John Chambers and coauthors. For R, the basic reference is <em class="emph">The New S Language: A Programming Environment for Data Analysis and Graphics</em> by Richard A. Becker, John M. Chambers and Allan R. Wilks. The new features of the 1991 release of S are covered in <em class="emph">Statistical Models in S</em> edited by John M. Chambers and Trevor J. Hastie. The formal methods and classes of the <strong class="strong">methods</strong> package are based on those described in <em class="emph">Programming with Data</em> by John M. Chambers. See <a class="xref" href="#References">References</a>, for precise references. </p> <p>There are now a number of books which describe how to use R for data analysis and statistics, and documentation for S/<small class="sc">S-PLUS</small> can typically be used with R, keeping the differences between the S implementations in mind. See <a data-manual="R-FAQ" href="R-FAQ.html#What-documentation-exists-for-R_003f">What documentation exists for R?</a> in <cite class="cite">R FAQ</cite>. </p> <hr> </div> <div class="section-level-extent" id="R-and-statistics"> <div class="nav-panel"> <p> Next: <a href="#R-and-the-window-system" accesskey="n" rel="next">R and the window system</a>, Previous: <a href="#Related-software-and-documentation" accesskey="p" rel="prev">Related software and documentation</a>, Up: <a href="#Introduction-and-preliminaries" accesskey="u" rel="up">Introduction and preliminaries</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="R-and-statistics-1"><span>1.3 R and statistics<a class="copiable-link" href="#R-and-statistics-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Packages"></a> <p>Our introduction to the R environment did not mention <em class="emph">statistics</em>, yet many people use R as a statistics system. We prefer to think of it of an environment within which many classical and modern statistical techniques have been implemented. A few of these are built into the base R environment, but many are supplied as <em class="emph">packages</em>. There are about 25 packages supplied with R (called “standard” and “recommended” packages) and many more are available through the <abbr class="acronym">CRAN</abbr> family of Internet sites (via <a class="uref" href="https://CRAN.R-project.org">https://CRAN.R-project.org</a>) and elsewhere. More details on packages are given later (see <a class="pxref" href="#Packages">Packages</a>). </p> <p>Most classical statistics and much of the latest methodology is available for use with R, but users may need to be prepared to do a little work to find it. </p> <p>There is an important difference in philosophy between S (and hence R) and the other main statistical systems. In S a statistical analysis is normally done as a series of steps, with intermediate results being stored in objects. Thus whereas SAS and SPSS will give copious output from a regression or discriminant analysis, R will give minimal output and store the results in a fit object for subsequent interrogation by further R functions. </p> <hr> </div> <div class="section-level-extent" id="R-and-the-window-system"> <div class="nav-panel"> <p> Next: <a href="#Using-R-interactively" accesskey="n" rel="next">Using R interactively</a>, Previous: <a href="#R-and-statistics" accesskey="p" rel="prev">R and statistics</a>, Up: <a href="#Introduction-and-preliminaries" accesskey="u" rel="up">Introduction and preliminaries</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="R-and-the-window-system-1"><span>1.4 R and the window system<a class="copiable-link" href="#R-and-the-window-system-1"> ¶</a></span></h3> <p>The most convenient way to use R is at a graphics workstation running a windowing system. This guide is aimed at users who have this facility. In particular we will occasionally refer to the use of R on an X window system although the vast bulk of what is said applies generally to any implementation of the R environment. </p> <p>Most users will find it necessary to interact directly with the operating system on their computer from time to time. In this guide, we mainly discuss interaction with the operating system on UNIX machines. If you are running R under Windows or macOS you will need to make some small adjustments. </p> <p>Setting up a workstation to take full advantage of the customizable features of R is a straightforward if somewhat tedious procedure, and will not be considered further here. Users in difficulty should seek local expert help. </p> <hr> </div> <div class="section-level-extent" id="Using-R-interactively"> <div class="nav-panel"> <p> Next: <a href="#Getting-help" accesskey="n" rel="next">Getting help with functions and features</a>, Previous: <a href="#R-and-the-window-system" accesskey="p" rel="prev">R and the window system</a>, Up: <a href="#Introduction-and-preliminaries" accesskey="u" rel="up">Introduction and preliminaries</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Using-R-interactively-1"><span>1.5 Using R interactively<a class="copiable-link" href="#Using-R-interactively-1"> ¶</a></span></h3> <p>When you use the R program it issues a prompt when it expects input commands. The default prompt is ‘<samp class="samp"><code class="code">></code></samp>’, which on UNIX might be the same as the shell prompt, and so it may appear that nothing is happening. However, as we shall see, it is easy to change to a different R prompt if you wish. We will assume that the UNIX shell prompt is ‘<samp class="samp"><code class="code">$</code></samp>’. </p> <p>In using R under UNIX the suggested procedure for the first occasion is as follows: </p> <ol class="enumerate"> <li> Create a separate sub-directory, say <samp class="file">work</samp>, to hold data files on which you will use R for this problem. This will be the working directory whenever you use R for this particular problem. <div class="example"> <pre class="example-preformatted">$ mkdir work $ cd work </pre></div> </li><li> Start the R program with the command <div class="example"> <pre class="example-preformatted">$ R </pre></div> </li><li> At this point R commands may be issued (see later). </li><li> To quit the R program the command is <div class="example"> <pre class="example-preformatted">> q() </pre></div> <p>At this point you will be asked whether you want to save the data from your R session. On some systems this will bring up a dialog box, and on others you will receive a text prompt to which you can respond <kbd class="kbd">yes</kbd>, <kbd class="kbd">no</kbd> or <kbd class="kbd">cancel</kbd> (a single letter abbreviation will do) to save the data before quitting, quit without saving, or return to the R session. Data which is saved will be available in future R sessions. </p> </li></ol> <p>Further R sessions are simple. </p> <ol class="enumerate"> <li> Make <samp class="file">work</samp> the working directory and start the program as before: <div class="example"> <pre class="example-preformatted">$ cd work $ R </pre></div> </li><li> Use the R program, terminating with the <code class="code">q()</code> command at the end of the session. </li></ol> <p>To use R under Windows the procedure to follow is basically the same. Create a folder as the working directory, and set that in the <samp class="file">Start In</samp> field in your R shortcut. Then launch R by double clicking on the icon. </p> </div> <div class="section-level-extent" id="An-introductory-session"> <h3 class="section"><span>1.6 An introductory session<a class="copiable-link" href="#An-introductory-session"> ¶</a></span></h3> <p>Readers wishing to get a feel for R at a computer before proceeding are strongly advised to work through the introductory session given in <a class="ref" href="#A-sample-session">A sample session</a>. </p> <hr> </div> <div class="section-level-extent" id="Getting-help"> <div class="nav-panel"> <p> Next: <a href="#R-commands_003b-case-sensitivity-etc" accesskey="n" rel="next">R commands, case sensitivity, etc.</a>, Previous: <a href="#Using-R-interactively" accesskey="p" rel="prev">Using R interactively</a>, Up: <a href="#Introduction-and-preliminaries" accesskey="u" rel="up">Introduction and preliminaries</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Getting-help-with-functions-and-features"><span>1.7 Getting help with functions and features<a class="copiable-link" href="#Getting-help-with-functions-and-features"> ¶</a></span></h3> <a class="index-entry-id" id="index-help"></a> <p>R has an inbuilt help facility similar to the <code class="code">man</code> facility of UNIX. To get more information on any specific named function, for example <code class="code">solve</code>, the command is </p> <div class="example"> <pre class="example-preformatted">> help(solve) </pre></div> <a class="index-entry-id" id="index-help-1"></a> <p>An alternative is </p> <div class="example"> <pre class="example-preformatted">> ?solve </pre></div> <a class="index-entry-id" id="index-_003f"></a> <p>For a feature specified by special characters, the argument must be enclosed in double or single quotes, making it a “character string”: This is also necessary for a few words with syntactic meaning including <code class="code">if</code>, <code class="code">for</code> and <code class="code">function</code>. </p> <div class="example"> <pre class="example-preformatted">> help("[[") </pre></div> <p>Either form of quote mark may be used to escape the other, as in the string <code class="code">"It's important"</code>. Our convention is to use double quote marks for preference. </p> <p>On most R installations help is available in <abbr class="acronym">HTML</abbr> format by running </p> <div class="example"> <pre class="example-preformatted">> help.start() </pre></div> <a class="index-entry-id" id="index-help_002estart"></a> <p>which will launch a Web browser that allows the help pages to be browsed with hyperlinks. On UNIX, subsequent help requests are sent to the <abbr class="acronym">HTML</abbr>-based help system. The ‘Search Engine and Keywords’ link in the page loaded by <code class="code">help.start()</code> is particularly useful as it is contains a high-level concept list which searches though available functions. It can be a great way to get your bearings quickly and to understand the breadth of what R has to offer. </p> <a class="index-entry-id" id="index-help_002esearch"></a> <p>The <code class="code">help.search</code> command (alternatively <code class="code">??</code>) allows searching for help in various ways. For example, </p> <div class="example"> <pre class="example-preformatted">> ??solve </pre></div> <a class="index-entry-id" id="index-_003f_003f"></a> <p>Try <code class="code">?help.search</code> for details and more examples. </p> <p>The examples on a help topic can normally be run by </p> <div class="example"> <pre class="example-preformatted">> example(<var class="var">topic</var>) </pre></div> <a class="index-entry-id" id="index-example"></a> <p>Windows versions of R have other optional help systems: use </p> <div class="example"> <pre class="example-preformatted">> ?help </pre></div> <p>for further details. </p> <hr> </div> <div class="section-level-extent" id="R-commands_003b-case-sensitivity-etc"> <div class="nav-panel"> <p> Next: <a href="#Recall-and-correction-of-previous-commands" accesskey="n" rel="next">Recall and correction of previous commands</a>, Previous: <a href="#Getting-help" accesskey="p" rel="prev">Getting help with functions and features</a>, Up: <a href="#Introduction-and-preliminaries" accesskey="u" rel="up">Introduction and preliminaries</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="R-commands_002c-case-sensitivity_002c-etc_002e"><span>1.8 R commands, case sensitivity, etc.<a class="copiable-link" href="#R-commands_002c-case-sensitivity_002c-etc_002e"> ¶</a></span></h3> <p>Technically R is an <em class="emph">expression language</em> with a very simple syntax. It is <em class="emph">case sensitive</em> as are most UNIX based packages, so <code class="code">A</code> and <code class="code">a</code> are different symbols and would refer to different variables. The set of symbols which can be used in R names depends on the operating system and country within which R is being run (technically on the <em class="emph">locale</em> in use). Normally all alphanumeric symbols are allowed<a class="footnote" id="DOCF2" href="#FOOT2"><sup>2</sup></a> (and in some countries this includes accented letters) plus ‘<samp class="samp"><code class="code">.</code></samp>’ and ‘<samp class="samp"><code class="code">_</code></samp>’, with the restriction that a name must start with ‘<samp class="samp"><code class="code">.</code></samp>’ or a letter, and if it starts with ‘<samp class="samp"><code class="code">.</code></samp>’ the second character must not be a digit. Names are effectively unlimited in length. </p> <p>Elementary commands consist of either <em class="emph">expressions</em> or <em class="emph">assignments</em>. If an expression is given as a command, it is evaluated, printed (unless specifically made invisible), and the value is lost. An assignment also evaluates an expression and passes the value to a variable but the result is not automatically printed. </p> <p>Commands are separated either by a semi-colon (‘<samp class="samp"><code class="code">;</code></samp>’), or by a newline. Elementary commands can be grouped together into one compound expression by braces (‘<samp class="samp"><code class="code">{</code></samp>’ and ‘<samp class="samp"><code class="code">}</code></samp>’). <em class="emph">Comments</em> can be put almost<a class="footnote" id="DOCF3" href="#FOOT3"><sup>3</sup></a> anywhere, starting with a hash mark (‘<samp class="samp"><code class="code">#</code></samp>’), everything to the end of the line is a comment. </p> <p>If a command is not complete at the end of a line, R will give a different prompt, by default </p> <div class="example"> <pre class="example-preformatted">+ </pre></div> <p>on second and subsequent lines and continue to read input until the command is syntactically complete. This prompt may be changed by the user. We will generally omit the continuation prompt and indicate continuation by simple indenting. </p> <p>Command lines entered at the console are limited<a class="footnote" id="DOCF4" href="#FOOT4"><sup>4</sup></a> to about 4095 bytes (not characters). </p> <hr> </div> <div class="section-level-extent" id="Recall-and-correction-of-previous-commands"> <div class="nav-panel"> <p> Next: <a href="#Executing-commands-from-or-diverting-output-to-a-file" accesskey="n" rel="next">Executing commands from or diverting output to a file</a>, Previous: <a href="#R-commands_003b-case-sensitivity-etc" accesskey="p" rel="prev">R commands, case sensitivity, etc.</a>, Up: <a href="#Introduction-and-preliminaries" accesskey="u" rel="up">Introduction and preliminaries</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Recall-and-correction-of-previous-commands-1"><span>1.9 Recall and correction of previous commands<a class="copiable-link" href="#Recall-and-correction-of-previous-commands-1"> ¶</a></span></h3> <p>Under many versions of UNIX and on Windows, R provides a mechanism for recalling and re-executing previous commands. The vertical arrow keys on the keyboard can be used to scroll forward and backward through a <em class="emph">command history</em>. Once a command is located in this way, the cursor can be moved within the command using the horizontal arrow keys, and characters can be removed with the <kbd class="key">DEL</kbd> key or added with the other keys. More details are provided later: see <a class="pxref" href="#The-command_002dline-editor">The command-line editor</a>. </p> <p>The recall and editing capabilities under UNIX are highly customizable. You can find out how to do this by reading the manual entry for the <strong class="strong">readline</strong> library. </p> <p>Alternatively, the Emacs text editor provides more general support mechanisms (via <abbr class="acronym">ESS</abbr>, <em class="emph">Emacs Speaks Statistics</em>) for working interactively with R. See <a data-manual="R-FAQ" href="R-FAQ.html#R-and-Emacs">R and Emacs</a> in <cite class="cite">R FAQ</cite>. </p> <hr> </div> <div class="section-level-extent" id="Executing-commands-from-or-diverting-output-to-a-file"> <div class="nav-panel"> <p> Next: <a href="#Data-permanency-and-removing-objects" accesskey="n" rel="next">Data permanency and removing objects</a>, Previous: <a href="#Recall-and-correction-of-previous-commands" accesskey="p" rel="prev">Recall and correction of previous commands</a>, Up: <a href="#Introduction-and-preliminaries" accesskey="u" rel="up">Introduction and preliminaries</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Executing-commands-from-or-diverting-output-to-a-file-1"><span>1.10 Executing commands from or diverting output to a file<a class="copiable-link" href="#Executing-commands-from-or-diverting-output-to-a-file-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Diverting-input-and-output"></a> <p>If commands<a class="footnote" id="DOCF5" href="#FOOT5"><sup>5</sup></a> are stored in an external file, say <samp class="file">commands.R</samp> in the working directory <samp class="file">work</samp>, they may be executed at any time in an R session with the command </p> <div class="example"> <pre class="example-preformatted">> source("commands.R") </pre></div> <a class="index-entry-id" id="index-source"></a> <p>For Windows <strong class="strong">Source</strong> is also available on the <strong class="strong">File</strong> menu. The function <code class="code">sink</code>, </p> <div class="example"> <pre class="example-preformatted">> sink("record.lis") </pre></div> <a class="index-entry-id" id="index-sink"></a> <p>will divert all subsequent output from the console to an external file, <samp class="file">record.lis</samp>. The command </p> <div class="example"> <pre class="example-preformatted">> sink() </pre></div> <p>restores it to the console once again. </p> <hr> </div> <div class="section-level-extent" id="Data-permanency-and-removing-objects"> <div class="nav-panel"> <p> Previous: <a href="#Executing-commands-from-or-diverting-output-to-a-file" accesskey="p" rel="prev">Executing commands from or diverting output to a file</a>, Up: <a href="#Introduction-and-preliminaries" accesskey="u" rel="up">Introduction and preliminaries</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Data-permanency-and-removing-objects-1"><span>1.11 Data permanency and removing objects<a class="copiable-link" href="#Data-permanency-and-removing-objects-1"> ¶</a></span></h3> <p>The entities that R creates and manipulates are known as <em class="emph">objects</em>. These may be variables, arrays of numbers, character strings, functions, or more general structures built from such components. </p> <p>During an R session, objects are created and stored by name (we discuss this process in the next section). The R command </p> <div class="example"> <pre class="example-preformatted">> objects() </pre></div> <p>(alternatively, <code class="code">ls()</code>) can be used to display the names of (most of) the objects which are currently stored within R. The collection of objects currently stored is called the <em class="emph">workspace</em>. <a class="index-entry-id" id="index-Workspace"></a> </p> <p>To remove objects the function <code class="code">rm</code> is available: </p> <div class="example"> <pre class="example-preformatted">> rm(x, y, z, ink, junk, temp, foo, bar) </pre></div> <a class="index-entry-id" id="index-rm"></a> <a class="index-entry-id" id="index-Removing-objects"></a> <p>All objects created during an R session can be stored permanently in a file for use in future R sessions. At the end of each R session you are given the opportunity to save all the currently available objects. If you indicate that you want to do this, the objects are written to a file called <samp class="file">.RData</samp><a class="footnote" id="DOCF6" href="#FOOT6"><sup>6</sup></a> in the current directory, and the command lines used in the session are saved to a file called <samp class="file">.Rhistory</samp>. </p> <p>When R is started at later time from the same directory it reloads the workspace from this file. At the same time the associated commands history is reloaded. </p> <p>It is recommended that you should use separate working directories for analyses conducted with R. It is quite common for objects with names <code class="code">x</code> and <code class="code">y</code> to be created during an analysis. Names like this are often meaningful in the context of a single analysis, but it can be quite hard to decide what they might be when the several analyses have been conducted in the same directory. </p> <hr> </div> </div> <div class="chapter-level-extent" id="Simple-manipulations-numbers-and-vectors"> <div class="nav-panel"> <p> Next: <a href="#Objects" accesskey="n" rel="next">Objects, their modes and attributes</a>, Previous: <a href="#Introduction-and-preliminaries" accesskey="p" rel="prev">Introduction and preliminaries</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="chapter" id="Simple-manipulations_003b-numbers-and-vectors"><span>2 Simple manipulations; numbers and vectors<a class="copiable-link" href="#Simple-manipulations_003b-numbers-and-vectors"> ¶</a></span></h2> <a class="index-entry-id" id="index-Vectors"></a> <ul class="mini-toc"> <li><a href="#Vectors-and-assignment" accesskey="1">Vectors and assignment</a></li> <li><a href="#Vector-arithmetic" accesskey="2">Vector arithmetic</a></li> <li><a href="#Generating-regular-sequences" accesskey="3">Generating regular sequences</a></li> <li><a href="#Logical-vectors" accesskey="4">Logical vectors</a></li> <li><a href="#Missing-values" accesskey="5">Missing values</a></li> <li><a href="#Character-vectors" accesskey="6">Character vectors</a></li> <li><a href="#Index-vectors" accesskey="7">Index vectors; selecting and modifying subsets of a data set</a></li> <li><a href="#Other-types-of-objects" accesskey="8">Other types of objects</a></li> </ul> <hr> <div class="section-level-extent" id="Vectors-and-assignment"> <div class="nav-panel"> <p> Next: <a href="#Vector-arithmetic" accesskey="n" rel="next">Vector arithmetic</a>, Previous: <a href="#Simple-manipulations-numbers-and-vectors" accesskey="p" rel="prev">Simple manipulations; numbers and vectors</a>, Up: <a href="#Simple-manipulations-numbers-and-vectors" accesskey="u" rel="up">Simple manipulations; numbers and vectors</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Vectors-and-assignment-1"><span>2.1 Vectors and assignment<a class="copiable-link" href="#Vectors-and-assignment-1"> ¶</a></span></h3> <p>R operates on named <em class="emph">data structures</em>. The simplest such structure is the numeric <em class="emph">vector</em>, which is a single entity consisting of an ordered collection of numbers. To set up a vector named <code class="code">x</code>, say, consisting of five numbers, namely 10.4, 5.6, 3.1, 6.4 and 21.7, use the R command </p> <div class="example"> <pre class="example-preformatted">> x <- c(10.4, 5.6, 3.1, 6.4, 21.7) </pre></div> <a class="index-entry-id" id="index-c"></a> <a class="index-entry-id" id="index-vector"></a> <p>This is an <em class="emph">assignment</em> statement using the <em class="emph">function</em> <code class="code">c()</code> which in this context can take an arbitrary number of vector <em class="emph">arguments</em> and whose value is a vector got by concatenating its arguments end to end.<a class="footnote" id="DOCF7" href="#FOOT7"><sup>7</sup></a> </p> <p>A number occurring by itself in an expression is taken as a vector of length one. </p> <p>Notice that the assignment operator (‘<samp class="samp"><code class="code"><-</code></samp>’), which consists of the two characters ‘<samp class="samp"><code class="code"><</code></samp>’ (“less than”) and ‘<samp class="samp"><code class="code">-</code></samp>’ (“minus”) occurring strictly side-by-side and it ‘points’ to the object receiving the value of the expression. In most contexts the ‘<samp class="samp"><code class="code">=</code></samp>’ operator can be used as an alternative. <a class="index-entry-id" id="index-Assignment"></a> </p> <p>Assignment can also be made using the function <code class="code">assign()</code>. An equivalent way of making the same assignment as above is with: </p> <div class="example"> <pre class="example-preformatted">> assign("x", c(10.4, 5.6, 3.1, 6.4, 21.7)) </pre></div> <p>The usual operator, <code class="code"><-</code>, can be thought of as a syntactic short-cut to this. </p> <p>Assignments can also be made in the other direction, using the obvious change in the assignment operator. So the same assignment could be made using </p> <div class="example"> <pre class="example-preformatted">> c(10.4, 5.6, 3.1, 6.4, 21.7) -> x </pre></div> <p>If an expression is used as a complete command, the value is printed <em class="emph">and lost</em><a class="footnote" id="DOCF8" href="#FOOT8"><sup>8</sup></a>. So now if we were to use the command </p> <div class="example"> <pre class="example-preformatted">> 1/x </pre></div> <p>the reciprocals of the five values would be printed at the terminal (and the value of <code class="code">x</code>, of course, unchanged). </p> <p>The further assignment </p> <div class="example"> <pre class="example-preformatted">> y <- c(x, 0, x) </pre></div> <p>would create a vector <code class="code">y</code> with 11 entries consisting of two copies of <code class="code">x</code> with a zero in the middle place. </p> <hr> </div> <div class="section-level-extent" id="Vector-arithmetic"> <div class="nav-panel"> <p> Next: <a href="#Generating-regular-sequences" accesskey="n" rel="next">Generating regular sequences</a>, Previous: <a href="#Vectors-and-assignment" accesskey="p" rel="prev">Vectors and assignment</a>, Up: <a href="#Simple-manipulations-numbers-and-vectors" accesskey="u" rel="up">Simple manipulations; numbers and vectors</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Vector-arithmetic-1"><span>2.2 Vector arithmetic<a class="copiable-link" href="#Vector-arithmetic-1"> ¶</a></span></h3> <p>Vectors can be used in arithmetic expressions, in which case the operations are performed element by element. Vectors occurring in the same expression need not all be of the same length. If they are not, the value of the expression is a vector with the same length as the longest vector which occurs in the expression. Shorter vectors in the expression are <em class="emph">recycled</em> as often as need be (perhaps fractionally) until they match the length of the longest vector. In particular a constant is simply repeated. So with the above assignments the command <a class="index-entry-id" id="index-Recycling-rule"></a> </p> <div class="example"> <pre class="example-preformatted">> v <- 2*x + y + 1 </pre></div> <p>generates a new vector <code class="code">v</code> of length 11 constructed by adding together, element by element, <code class="code">2*x</code> repeated 2.2 times, <code class="code">y</code> repeated just once, and <code class="code">1</code> repeated 11 times. </p> <a class="index-entry-id" id="index-Arithmetic-functions-and-operators"></a> <p>The elementary arithmetic operators are the usual <code class="code">+</code>, <code class="code">-</code>, <code class="code">*</code>, <code class="code">/</code> and <code class="code">^</code> for raising to a power. <a class="index-entry-id" id="index-_002b"></a> <a class="index-entry-id" id="index-_002d"></a> <a class="index-entry-id" id="index-_002a"></a> <a class="index-entry-id" id="index-_002f"></a> <a class="index-entry-id" id="index-_005e"></a> In addition all of the common arithmetic functions are available. <code class="code">log</code>, <code class="code">exp</code>, <code class="code">sin</code>, <code class="code">cos</code>, <code class="code">tan</code>, <code class="code">sqrt</code>, and so on, all have their usual meaning. <a class="index-entry-id" id="index-log"></a> <a class="index-entry-id" id="index-exp"></a> <a class="index-entry-id" id="index-sin"></a> <a class="index-entry-id" id="index-cos"></a> <a class="index-entry-id" id="index-tan"></a> <a class="index-entry-id" id="index-sqrt"></a> <code class="code">max</code> and <code class="code">min</code> select the largest and smallest elements of a vector respectively. <a class="index-entry-id" id="index-max"></a> <a class="index-entry-id" id="index-min"></a> <code class="code">range</code> is a function whose value is a vector of length two, namely <code class="code">c(min(x), max(x))</code>. <a class="index-entry-id" id="index-range"></a> <code class="code">length(x)</code> is the number of elements in <code class="code">x</code>, <a class="index-entry-id" id="index-length"></a> <code class="code">sum(x)</code> gives the total of the elements in <code class="code">x</code>, <a class="index-entry-id" id="index-sum"></a> and <code class="code">prod(x)</code> their product. <a class="index-entry-id" id="index-prod"></a> </p> <p>Two statistical functions are <code class="code">mean(x)</code> which calculates the sample mean, which is the same as <code class="code">sum(x)/length(x)</code>, <a class="index-entry-id" id="index-mean"></a> and <code class="code">var(x)</code> which gives </p> <div class="example"> <pre class="example-preformatted">sum((x-mean(x))^2)/(length(x)-1) </pre></div> <a class="index-entry-id" id="index-var"></a> <p>or sample variance. If the argument to <code class="code">var()</code> is an <em class="math">n</em>-by-<em class="math">p</em> matrix the value is a <em class="math">p</em>-by-<em class="math">p</em> sample covariance matrix got by regarding the rows as independent <em class="math">p</em>-variate sample vectors. </p> <p><code class="code">sort(x)</code> returns a vector of the same size as <code class="code">x</code> with the elements arranged in increasing order; however there are other more flexible sorting facilities available (see <code class="code">order()</code> or <code class="code">sort.list()</code> which produce a permutation to do the sorting). <a class="index-entry-id" id="index-sort"></a> <a class="index-entry-id" id="index-order"></a> </p> <p>Note that <code class="code">max</code> and <code class="code">min</code> select the largest and smallest values in their arguments, even if they are given several vectors. The <em class="emph">parallel</em> maximum and minimum functions <code class="code">pmax</code> and <code class="code">pmin</code> return a vector (of length equal to their longest argument) that contains in each element the largest (smallest) element in that position in any of the input vectors. <a class="index-entry-id" id="index-pmax"></a> <a class="index-entry-id" id="index-pmin"></a> </p> <p>For most purposes the user will not be concerned if the “numbers” in a numeric vector are integers, reals or even complex. Internally calculations are done as double precision real numbers, or double precision complex numbers if the input data are complex. </p> <p>To work with complex numbers, supply an explicit complex part. Thus </p> <div class="example"> <pre class="example-preformatted">sqrt(-17) </pre></div> <p>will give <code class="code">NaN</code> and a warning, but </p> <div class="example"> <pre class="example-preformatted">sqrt(-17+0i) </pre></div> <p>will do the computations as complex numbers. </p> <hr> </div> <div class="section-level-extent" id="Generating-regular-sequences"> <div class="nav-panel"> <p> Next: <a href="#Logical-vectors" accesskey="n" rel="next">Logical vectors</a>, Previous: <a href="#Vector-arithmetic" accesskey="p" rel="prev">Vector arithmetic</a>, Up: <a href="#Simple-manipulations-numbers-and-vectors" accesskey="u" rel="up">Simple manipulations; numbers and vectors</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Generating-regular-sequences-1"><span>2.3 Generating regular sequences<a class="copiable-link" href="#Generating-regular-sequences-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Regular-sequences"></a> <p>R has a number of facilities for generating commonly used sequences of numbers. For example <code class="code">1:30</code> is the vector <code class="code">c(1, 2, …, 29, 30)</code>. <a class="index-entry-id" id="index-_003a"></a> The colon operator has high priority within an expression, so, for example <code class="code">2*1:15</code> is the vector <code class="code">c(2, 4, …, 28, 30)</code>. Put <code class="code">n <- 10</code> and compare the sequences <code class="code">1:n-1</code> and <code class="code">1:(n-1)</code>. </p> <p>The construction <code class="code">30:1</code> may be used to generate a sequence backwards. </p> <a class="index-entry-id" id="index-seq"></a> <p>The function <code class="code">seq()</code> is a more general facility for generating sequences. It has five arguments, only some of which may be specified in any one call. The first two arguments, if given, specify the beginning and end of the sequence, and if these are the only two arguments given the result is the same as the colon operator. That is <code class="code">seq(2,10)</code> is the same vector as <code class="code">2:10</code>. </p> <p>Arguments to <code class="code">seq()</code>, and to many other R functions, can also be given in named form, in which case the order in which they appear is irrelevant. The first two arguments may be named <code class="code">from=<var class="var">value</var></code> and <code class="code">to=<var class="var">value</var></code>; thus <code class="code">seq(1,30)</code>, <code class="code">seq(from=1, to=30)</code> and <code class="code">seq(to=30, from=1)</code> are all the same as <code class="code">1:30</code>. The next two arguments to <code class="code">seq()</code> may be named <code class="code">by=<var class="var">value</var></code> and <code class="code">length=<var class="var">value</var></code>, which specify a step size and a length for the sequence respectively. If neither of these is given, the default <code class="code">by=1</code> is assumed. </p> <p>For example </p> <div class="example"> <pre class="example-preformatted">> seq(-5, 5, by=.2) -> s3 </pre></div> <p>generates in <code class="code">s3</code> the vector <code class="code">c(-5.0, -4.8, -4.6, …, 4.6, 4.8, 5.0)</code>. Similarly </p> <div class="example"> <pre class="example-preformatted">> s4 <- seq(length=51, from=-5, by=.2) </pre></div> <p>generates the same vector in <code class="code">s4</code>. </p> <p>The fifth argument may be named <code class="code">along=<var class="var">vector</var></code>, which is normally used as the only argument to create the sequence <code class="code">1, 2, …, length(<var class="var">vector</var>)</code>, or the empty sequence if the vector is empty (as it can be). </p> <p>A related function is <code class="code">rep()</code> <a class="index-entry-id" id="index-rep"></a> which can be used for replicating an object in various complicated ways. The simplest form is </p> <div class="example"> <pre class="example-preformatted">> s5 <- rep(x, times=5) </pre></div> <p>which will put five copies of <code class="code">x</code> end-to-end in <code class="code">s5</code>. Another useful version is </p> <div class="example"> <pre class="example-preformatted">> s6 <- rep(x, each=5) </pre></div> <p>which repeats each element of <code class="code">x</code> five times before moving on to the next. </p> <hr> </div> <div class="section-level-extent" id="Logical-vectors"> <div class="nav-panel"> <p> Next: <a href="#Missing-values" accesskey="n" rel="next">Missing values</a>, Previous: <a href="#Generating-regular-sequences" accesskey="p" rel="prev">Generating regular sequences</a>, Up: <a href="#Simple-manipulations-numbers-and-vectors" accesskey="u" rel="up">Simple manipulations; numbers and vectors</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Logical-vectors-1"><span>2.4 Logical vectors<a class="copiable-link" href="#Logical-vectors-1"> ¶</a></span></h3> <p>As well as numerical vectors, R allows manipulation of logical quantities. The elements of a logical vector can have the values <code class="code">TRUE</code>, <code class="code">FALSE</code>, and <code class="code">NA</code> (for “not available”, see below). The first two are often abbreviated as <code class="code">T</code> and <code class="code">F</code>, respectively. Note however that <code class="code">T</code> and <code class="code">F</code> are just variables which are set to <code class="code">TRUE</code> and <code class="code">FALSE</code> by default, but are not reserved words and hence can be overwritten by the user. Hence, you should always use <code class="code">TRUE</code> and <code class="code">FALSE</code>. <a class="index-entry-id" id="index-FALSE"></a> <a class="index-entry-id" id="index-TRUE"></a> <a class="index-entry-id" id="index-F"></a> <a class="index-entry-id" id="index-T"></a> </p> <p>Logical vectors are generated by <em class="emph">conditions</em>. For example </p> <div class="example"> <pre class="example-preformatted">> temp <- x > 13 </pre></div> <p>sets <code class="code">temp</code> as a vector of the same length as <code class="code">x</code> with values <code class="code">FALSE</code> corresponding to elements of <code class="code">x</code> where the condition is <em class="emph">not</em> met and <code class="code">TRUE</code> where it is. </p> <p>The logical operators are <code class="code"><</code>, <code class="code"><=</code>, <code class="code">></code>, <code class="code">>=</code>, <code class="code">==</code> for exact equality and <code class="code">!=</code> for inequality. <a class="index-entry-id" id="index-_003c"></a> <a class="index-entry-id" id="index-_003c_003d"></a> <a class="index-entry-id" id="index-_003e"></a> <a class="index-entry-id" id="index-_003e_003d"></a> <a class="index-entry-id" id="index-_003d_003d"></a> <a class="index-entry-id" id="index-_0021_003d"></a> In addition if <code class="code">c1</code> and <code class="code">c2</code> are logical expressions, then <code class="code">c1 & c2</code><!-- /@w --> is their intersection (<em class="emph">“and”</em>), <code class="code">c1 | c2</code><!-- /@w --> is their union (<em class="emph">“or”</em>), and <code class="code">!c1</code> is the negation of <code class="code">c1</code>. <a class="index-entry-id" id="index-_0021"></a> <a class="index-entry-id" id="index-_007c"></a> <a class="index-entry-id" id="index-_0026"></a> </p> <p>Logical vectors may be used in ordinary arithmetic, in which case they are <em class="emph">coerced</em> into numeric vectors, <code class="code">FALSE</code> becoming <code class="code">0</code> and <code class="code">TRUE</code> becoming <code class="code">1</code>. However there are situations where logical vectors and their coerced numeric counterparts are not equivalent, for example see the next subsection. </p> <hr> </div> <div class="section-level-extent" id="Missing-values"> <div class="nav-panel"> <p> Next: <a href="#Character-vectors" accesskey="n" rel="next">Character vectors</a>, Previous: <a href="#Logical-vectors" accesskey="p" rel="prev">Logical vectors</a>, Up: <a href="#Simple-manipulations-numbers-and-vectors" accesskey="u" rel="up">Simple manipulations; numbers and vectors</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Missing-values-1"><span>2.5 Missing values<a class="copiable-link" href="#Missing-values-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Missing-values"></a> <p>In some cases the components of a vector may not be completely known. When an element or value is “not available” or a “missing value” in the statistical sense, a place within a vector may be reserved for it by assigning it the special value <code class="code">NA</code>. <a class="index-entry-id" id="index-NA"></a> In general any operation on an <code class="code">NA</code> becomes an <code class="code">NA</code>. The motivation for this rule is simply that if the specification of an operation is incomplete, the result cannot be known and hence is not available. </p> <a class="index-entry-id" id="index-is_002ena"></a> <p>The function <code class="code">is.na(x)</code> gives a logical vector of the same size as <code class="code">x</code> with value <code class="code">TRUE</code> if and only if the corresponding element in <code class="code">x</code> is <code class="code">NA</code>. </p> <div class="example"> <pre class="example-preformatted">> z <- c(1:3,NA); ind <- is.na(z) </pre></div> <p>Notice that the logical expression <code class="code">x == NA</code> is quite different from <code class="code">is.na(x)</code> since <code class="code">NA</code> is not really a value but a marker for a quantity that is not available. Thus <code class="code">x == NA</code> is a vector of the same length as <code class="code">x</code> <em class="emph">all</em> of whose values are <code class="code">NA</code> as the logical expression itself is incomplete and hence undecidable. </p> <p>Note that there is a second kind of “missing” values which are produced by numerical computation, the so-called <em class="emph">Not a Number</em>, <code class="code">NaN</code>, <a class="index-entry-id" id="index-NaN"></a> values. Examples are </p> <div class="example"> <pre class="example-preformatted">> 0/0 </pre></div> <p>or </p> <div class="example"> <pre class="example-preformatted">> Inf - Inf </pre></div> <p>which both give <code class="code">NaN</code> since the result cannot be defined sensibly. </p> <p>In summary, <code class="code">is.na(xx)</code> is <code class="code">TRUE</code> <em class="emph">both</em> for <code class="code">NA</code> and <code class="code">NaN</code> values. To differentiate these, <code class="code">is.nan(xx)</code> is only <code class="code">TRUE</code> for <code class="code">NaN</code>s. <a class="index-entry-id" id="index-is_002enan"></a> </p> <p>Missing values are sometimes printed as <code class="code"><NA></code> when character vectors are printed without quotes. </p> <hr> </div> <div class="section-level-extent" id="Character-vectors"> <div class="nav-panel"> <p> Next: <a href="#Index-vectors" accesskey="n" rel="next">Index vectors; selecting and modifying subsets of a data set</a>, Previous: <a href="#Missing-values" accesskey="p" rel="prev">Missing values</a>, Up: <a href="#Simple-manipulations-numbers-and-vectors" accesskey="u" rel="up">Simple manipulations; numbers and vectors</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Character-vectors-1"><span>2.6 Character vectors<a class="copiable-link" href="#Character-vectors-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Character-vectors"></a> <p>Character quantities and character vectors are used frequently in R, for example as plot labels. Where needed they are denoted by a sequence of characters delimited by the double quote character, e.g., <code class="code">"x-values"</code>, <code class="code">"New iteration results"</code>. </p> <p>Character strings are entered using either matching double (<code class="code">"</code>) or single (<code class="code">'</code>) quotes, but are printed using double quotes (or sometimes without quotes). They use C-style escape sequences, using <code class="code">\</code> as the escape character, so <code class="code">\</code> is entered and printed as <code class="code">\\</code>, and inside double quotes <code class="code">"</code> is entered as <code class="code">\"</code>. Other useful escape sequences are <code class="code">\n</code>, newline, <code class="code">\t</code>, tab and <code class="code">\b</code>, backspace—see <code class="command">?Quotes</code> for a full list. </p> <p>Character vectors may be concatenated into a vector by the <code class="code">c()</code> function; examples of their use will emerge frequently. <a class="index-entry-id" id="index-c-1"></a> </p> <a class="index-entry-id" id="index-paste"></a> <p>The <code class="code">paste()</code> function takes an arbitrary number of arguments and concatenates them one by one into character strings. Any numbers given among the arguments are coerced into character strings in the evident way, that is, in the same way they would be if they were printed. The arguments are by default separated in the result by a single blank character, but this can be changed by the named argument, <code class="code">sep=<var class="var">string</var></code>, which changes it to <code class="code"><var class="var">string</var></code>, possibly empty. </p> <p>For example </p> <div class="example"> <pre class="example-preformatted">> labs <- paste(c("X","Y"), 1:10, sep="") </pre></div> <p>makes <code class="code">labs</code> into the character vector </p> <div class="example"> <pre class="example-preformatted">c("X1", "Y2", "X3", "Y4", "X5", "Y6", "X7", "Y8", "X9", "Y10") </pre></div> <p>Note particularly that recycling of short lists takes place here too; thus <code class="code">c("X", "Y")</code> is repeated 5 times to match the sequence <code class="code">1:10</code>. <a class="footnote" id="DOCF9" href="#FOOT9"><sup>9</sup></a> </p> <hr> </div> <div class="section-level-extent" id="Index-vectors"> <div class="nav-panel"> <p> Next: <a href="#Other-types-of-objects" accesskey="n" rel="next">Other types of objects</a>, Previous: <a href="#Character-vectors" accesskey="p" rel="prev">Character vectors</a>, Up: <a href="#Simple-manipulations-numbers-and-vectors" accesskey="u" rel="up">Simple manipulations; numbers and vectors</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Index-vectors_003b-selecting-and-modifying-subsets-of-a-data-set"><span>2.7 Index vectors; selecting and modifying subsets of a data set<a class="copiable-link" href="#Index-vectors_003b-selecting-and-modifying-subsets-of-a-data-set"> ¶</a></span></h3> <a class="index-entry-id" id="index-Indexing-vectors"></a> <p>Subsets of the elements of a vector may be selected by appending to the name of the vector an <em class="emph">index vector</em> in square brackets. More generally any expression that evaluates to a vector may have subsets of its elements similarly selected by appending an index vector in square brackets immediately after the expression. </p> <p>Such index vectors can be any of four distinct types. </p> <ol class="enumerate"> <li> <strong class="strong">A logical vector</strong>. In this case the index vector is recycled to the same length as the vector from which elements are to be selected. Values corresponding to <code class="code">TRUE</code> in the index vector are selected and those corresponding to <code class="code">FALSE</code> are omitted. For example <div class="example"> <pre class="example-preformatted">> y <- x[!is.na(x)] </pre></div> <p>creates (or re-creates) an object <code class="code">y</code> which will contain the non-missing values of <code class="code">x</code>, in the same order. Note that if <code class="code">x</code> has missing values, <code class="code">y</code> will be shorter than <code class="code">x</code>. Also </p> <div class="example"> <pre class="example-preformatted">> (x+1)[(!is.na(x)) & x>0] -> z </pre></div> <p>creates an object <code class="code">z</code> and places in it the values of the vector <code class="code">x+1</code> for which the corresponding value in <code class="code">x</code> was both non-missing and positive. </p> </li><li> <strong class="strong">A vector of positive integral quantities</strong>. In this case the values in the index vector must lie in the set {1, 2, …, <code class="code">length(x)</code>}. The corresponding elements of the vector are selected and concatenated, <em class="emph">in that order</em>, in the result. The index vector can be of any length and the result is of the same length as the index vector. For example <code class="code">x[6]</code> is the sixth component of <code class="code">x</code> and <div class="example"> <pre class="example-preformatted">> x[1:10] </pre></div> <p>selects the first 10 elements of <code class="code">x</code> (assuming <code class="code">length(x)</code> is not less than 10). Also </p> <div class="example"> <pre class="example-preformatted">> c("x","y")[rep(c(1,2,2,1), times=4)] </pre></div> <p>(an admittedly unlikely thing to do) produces a character vector of length 16 consisting of <code class="code">"x", "y", "y", "x"</code> repeated four times. </p> </li><li> <strong class="strong">A vector of negative integral quantities</strong>. Such an index vector specifies the values to be <em class="emph">excluded</em> rather than included. Thus <div class="example"> <pre class="example-preformatted">> y <- x[-(1:5)] </pre></div> <p>gives <code class="code">y</code> all but the first five elements of <code class="code">x</code>. </p> </li><li> <strong class="strong">A vector of character strings</strong>. This possibility only applies where an object has a <code class="code">names</code> attribute to identify its components. In this case a sub-vector of the names vector may be used in the same way as the positive integral labels in item 2 further above. <div class="example"> <pre class="example-preformatted">> fruit <- c(5, 10, 1, 20) > names(fruit) <- c("orange", "banana", "apple", "peach") > lunch <- fruit[c("apple","orange")] </pre></div> <p>The advantage is that alphanumeric <em class="emph">names</em> are often easier to remember than <em class="emph">numeric indices</em>. This option is particularly useful in connection with data frames, as we shall see later. </p> </li></ol> <p>An indexed expression can also appear on the receiving end of an assignment, in which case the assignment operation is performed <em class="emph">only on those elements of the vector</em>. The expression must be of the form <code class="code">vector[<var class="var">index_vector</var>]</code> as having an arbitrary expression in place of the vector name does not make much sense here. </p> <p>For example </p> <div class="example"> <pre class="example-preformatted">> x[is.na(x)] <- 0 </pre></div> <p>replaces any missing values in <code class="code">x</code> by zeros and </p> <div class="example"> <pre class="example-preformatted">> y[y < 0] <- -y[y < 0] </pre></div> <p>has the same effect as </p> <div class="example"> <pre class="example-preformatted">> y <- abs(y) </pre></div> <hr> </div> <div class="section-level-extent" id="Other-types-of-objects"> <div class="nav-panel"> <p> Previous: <a href="#Index-vectors" accesskey="p" rel="prev">Index vectors; selecting and modifying subsets of a data set</a>, Up: <a href="#Simple-manipulations-numbers-and-vectors" accesskey="u" rel="up">Simple manipulations; numbers and vectors</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Other-types-of-objects-1"><span>2.8 Other types of objects<a class="copiable-link" href="#Other-types-of-objects-1"> ¶</a></span></h3> <p>Vectors are the most important type of object in R, but there are several others which we will meet more formally in later sections. </p> <ul class="itemize mark-bullet"> <li><em class="emph">matrices</em> or more generally <em class="emph">arrays</em> are multi-dimensional generalizations of vectors. In fact, they <em class="emph">are</em> vectors that can be indexed by two or more indices and will be printed in special ways. See <a class="xref" href="#Arrays-and-matrices">Arrays and matrices</a>. </li><li><em class="emph">factors</em> provide compact ways to handle categorical data. See <a class="xref" href="#Factors">Ordered and unordered factors</a>. </li><li><em class="emph">lists</em> are a general form of vector in which the various elements need not be of the same type, and are often themselves vectors or lists. Lists provide a convenient way to return the results of a statistical computation. See <a class="xref" href="#Lists">Lists</a>. </li><li><em class="emph">data frames</em> are matrix-like structures, in which the columns can be of different types. Think of data frames as ‘data matrices’ with one row per observational unit but with (possibly) both numerical and categorical variables. Many experiments are best described by data frames: the treatments are categorical but the response is numeric. See <a class="xref" href="#Data-frames">Data frames</a>. </li><li><em class="emph">functions</em> are themselves objects in R which can be stored in the project’s workspace. This provides a simple and convenient way to extend R. See <a class="xref" href="#Writing-your-own-functions">Writing your own functions</a>. </li></ul> <hr> </div> </div> <div class="chapter-level-extent" id="Objects"> <div class="nav-panel"> <p> Next: <a href="#Factors" accesskey="n" rel="next">Ordered and unordered factors</a>, Previous: <a href="#Simple-manipulations-numbers-and-vectors" accesskey="p" rel="prev">Simple manipulations; numbers and vectors</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="chapter" id="Objects_002c-their-modes-and-attributes"><span>3 Objects, their modes and attributes<a class="copiable-link" href="#Objects_002c-their-modes-and-attributes"> ¶</a></span></h2> <a class="index-entry-id" id="index-Objects"></a> <a class="index-entry-id" id="index-Attributes"></a> <ul class="mini-toc"> <li><a href="#The-intrinsic-attributes-mode-and-length" accesskey="1">Intrinsic attributes: mode and length</a></li> <li><a href="#Changing-the-length-of-an-object" accesskey="2">Changing the length of an object</a></li> <li><a href="#Getting-and-setting-attributes" accesskey="3">Getting and setting attributes</a></li> <li><a href="#The-class-of-an-object" accesskey="4">The class of an object</a></li> </ul> <hr> <div class="section-level-extent" id="The-intrinsic-attributes-mode-and-length"> <div class="nav-panel"> <p> Next: <a href="#Changing-the-length-of-an-object" accesskey="n" rel="next">Changing the length of an object</a>, Previous: <a href="#Objects" accesskey="p" rel="prev">Objects, their modes and attributes</a>, Up: <a href="#Objects" accesskey="u" rel="up">Objects, their modes and attributes</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Intrinsic-attributes_003a-mode-and-length"><span>3.1 Intrinsic attributes: mode and length<a class="copiable-link" href="#Intrinsic-attributes_003a-mode-and-length"> ¶</a></span></h3> <p>The entities R operates on are technically known as <em class="emph">objects</em>. Examples are vectors of numeric (real) or complex values, vectors of logical values and vectors of character strings. These are known as “atomic” structures since their components are all of the same type, or <em class="emph">mode</em>, namely <em class="emph">numeric</em><a class="footnote" id="DOCF10" href="#FOOT10"><sup>10</sup></a>, <em class="emph">complex</em>, <em class="emph">logical</em>, <em class="emph">character</em> and <em class="emph">raw</em>. </p> <p>Vectors must have their values <em class="emph">all of the same mode</em>. Thus any given vector must be unambiguously either <em class="emph">logical</em>, <em class="emph">numeric</em>, <em class="emph">complex</em>, <em class="emph">character</em> or <em class="emph">raw</em>. (The only apparent exception to this rule is the special “value” listed as <code class="code">NA</code> for quantities not available, but in fact there are several types of <code class="code">NA</code>). Note that a vector can be empty and still have a mode. For example the empty character string vector is listed as <code class="code">character(0)</code> and the empty numeric vector as <code class="code">numeric(0)</code>. </p> <p>R also operates on objects called <em class="emph">lists</em>, which are of mode <em class="emph">list</em>. These are ordered sequences of objects which individually can be of any mode. <em class="emph">lists</em> are known as “recursive” rather than atomic structures since their components can themselves be lists in their own right. </p> <p>The other recursive structures are those of mode <em class="emph">function</em> and <em class="emph">expression</em>. Functions are the objects that form part of the R system along with similar user written functions, which we discuss in some detail later. Expressions as objects form an advanced part of R which will not be discussed in this guide, except indirectly when we discuss <em class="emph">formulae</em> used with modeling in R. </p> <p>By the <em class="emph">mode</em> of an object we mean the basic type of its fundamental constituents. This is a special case of a “property” of an object. Another property of every object is its <em class="emph">length</em>. The functions <code class="code">mode(<var class="var">object</var>)</code> and <code class="code">length(<var class="var">object</var>)</code> can be used to find out the mode and length of any defined structure <a class="footnote" id="DOCF11" href="#FOOT11"><sup>11</sup></a>. </p> <p>Further properties of an object are usually provided by <code class="code">attributes(<var class="var">object</var>)</code>, see <a class="ref" href="#Getting-and-setting-attributes">Getting and setting attributes</a>. Because of this, <em class="emph">mode</em> and <em class="emph">length</em> are also called “intrinsic attributes” of an object. <a class="index-entry-id" id="index-mode"></a> <a class="index-entry-id" id="index-length-1"></a> </p> <p>For example, if <code class="code">z</code> is a complex vector of length 100, then in an expression <code class="code">mode(z)</code> is the character string <code class="code">"complex"</code> and <code class="code">length(z)</code> is <code class="code">100</code>. </p> <p>R caters for changes of mode almost anywhere it could be considered sensible to do so, (and a few where it might not be). For example with </p> <div class="example"> <pre class="example-preformatted">> z <- 0:9 </pre></div> <p>we could put </p> <div class="example"> <pre class="example-preformatted">> digits <- as.character(z) </pre></div> <p>after which <code class="code">digits</code> is the character vector <code class="code">c("0", "1", "2", …, "9")</code>. A further <em class="emph">coercion</em>, or change of mode, reconstructs the numerical vector again: </p> <div class="example"> <pre class="example-preformatted">> d <- as.integer(digits) </pre></div> <p>Now <code class="code">d</code> and <code class="code">z</code> are the same.<a class="footnote" id="DOCF12" href="#FOOT12"><sup>12</sup></a> There is a large collection of functions of the form <code class="code">as.<var class="var">something</var>()</code> for either coercion from one mode to another, or for investing an object with some other attribute it may not already possess. The reader should consult the different help files to become familiar with them. </p> <hr> </div> <div class="section-level-extent" id="Changing-the-length-of-an-object"> <div class="nav-panel"> <p> Next: <a href="#Getting-and-setting-attributes" accesskey="n" rel="next">Getting and setting attributes</a>, Previous: <a href="#The-intrinsic-attributes-mode-and-length" accesskey="p" rel="prev">Intrinsic attributes: mode and length</a>, Up: <a href="#Objects" accesskey="u" rel="up">Objects, their modes and attributes</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Changing-the-length-of-an-object-1"><span>3.2 Changing the length of an object<a class="copiable-link" href="#Changing-the-length-of-an-object-1"> ¶</a></span></h3> <p>An “empty” object may still have a mode. For example </p> <div class="example"> <pre class="example-preformatted">> e <- numeric() </pre></div> <p>makes <code class="code">e</code> an empty vector structure of mode numeric. Similarly <code class="code">character()</code> is a empty character vector, and so on. Once an object of any size has been created, new components may be added to it simply by giving it an index value outside its previous range. Thus </p> <div class="example"> <pre class="example-preformatted">> e[3] <- 17 </pre></div> <p>now makes <code class="code">e</code> a vector of length 3, (the first two components of which are at this point both <code class="code">NA</code>). This applies to any structure at all, provided the mode of the additional component(s) agrees with the mode of the object in the first place. </p> <p>This automatic adjustment of lengths of an object is used often, for example in the <code class="code">scan()</code> function for input. (see <a class="pxref" href="#The-scan_0028_0029-function">The <code class="code">scan()</code> function</a>.) </p> <p>Conversely to truncate the size of an object requires only an assignment to do so. Hence if <code class="code">alpha</code> is an object of length 10, then </p> <div class="example"> <pre class="example-preformatted">> alpha <- alpha[2 * 1:5] </pre></div> <p>makes it an object of length 5 consisting of just the former components with even index. (The old indices are not retained, of course.) We can then retain just the first three values by </p> <div class="example"> <pre class="example-preformatted">> length(alpha) <- 3 </pre></div> <p>and vectors can be extended (by missing values) in the same way. </p> <hr> </div> <div class="section-level-extent" id="Getting-and-setting-attributes"> <div class="nav-panel"> <p> Next: <a href="#The-class-of-an-object" accesskey="n" rel="next">The class of an object</a>, Previous: <a href="#Changing-the-length-of-an-object" accesskey="p" rel="prev">Changing the length of an object</a>, Up: <a href="#Objects" accesskey="u" rel="up">Objects, their modes and attributes</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Getting-and-setting-attributes-1"><span>3.3 Getting and setting attributes<a class="copiable-link" href="#Getting-and-setting-attributes-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-attr"></a> <a class="index-entry-id" id="index-attributes"></a> <p>The function <code class="code">attributes(<var class="var">object</var>)</code> <a class="index-entry-id" id="index-attributes-1"></a> returns a list of all the non-intrinsic attributes currently defined for that object. The function <code class="code">attr(<var class="var">object</var>, <var class="var">name</var>)</code> <a class="index-entry-id" id="index-attr-1"></a> can be used to select a specific attribute. These functions are rarely used, except in rather special circumstances when some new attribute is being created for some particular purpose, for example to associate a creation date or an operator with an R object. The concept, however, is very important. </p> <p>Some care should be exercised when assigning or deleting attributes since they are an integral part of the object system used in R. </p> <p>When it is used on the left hand side of an assignment it can be used either to associate a new attribute with <code class="code"><var class="var">object</var></code> or to change an existing one. For example </p> <div class="example"> <pre class="example-preformatted">> attr(z, "dim") <- c(10,10) </pre></div> <p>allows R to treat <code class="code">z</code> as if it were a 10-by-10 matrix. </p> <hr> </div> <div class="section-level-extent" id="The-class-of-an-object"> <div class="nav-panel"> <p> Previous: <a href="#Getting-and-setting-attributes" accesskey="p" rel="prev">Getting and setting attributes</a>, Up: <a href="#Objects" accesskey="u" rel="up">Objects, their modes and attributes</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="The-class-of-an-object-1"><span>3.4 The class of an object<a class="copiable-link" href="#The-class-of-an-object-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Classes"></a> <p>All objects in R have a <em class="emph">class</em>, reported by the function <code class="code">class</code>. For simple vectors this is just the mode, for example <code class="code">"numeric"</code>, <code class="code">"logical"</code>, <code class="code">"character"</code> or <code class="code">"list"</code>, but <code class="code">"matrix"</code>, <code class="code">"array"</code>, <code class="code">"factor"</code> and <code class="code">"data.frame"</code> are other possible values. </p> <p>A special attribute known as the <em class="emph">class</em> of the object is used to allow for an object-oriented style<a class="footnote" id="DOCF13" href="#FOOT13"><sup>13</sup></a> of programming in R. For example if an object has class <code class="code">"data.frame"</code>, it will be printed in a certain way, the <code class="code">plot()</code> function will display it graphically in a certain way, and other so-called generic functions such as <code class="code">summary()</code> will react to it as an argument in a way sensitive to its class. </p> <p>To remove temporarily the effects of class, use the function <code class="code">unclass()</code>. <a class="index-entry-id" id="index-unclass"></a> For example if <code class="code">winter</code> has the class <code class="code">"data.frame"</code> then </p> <div class="example"> <pre class="example-preformatted">> winter </pre></div> <p>will print it in data frame form, which is rather like a matrix, whereas </p> <div class="example"> <pre class="example-preformatted">> unclass(winter) </pre></div> <p>will print it as an ordinary list. Only in rather special situations do you need to use this facility, but one is when you are learning to come to terms with the idea of class and generic functions. </p> <p>Generic functions and classes will be discussed further in <a class="ref" href="#Object-orientation">Classes, generic functions and object orientation</a>, but only briefly. </p> <hr> </div> </div> <div class="chapter-level-extent" id="Factors"> <div class="nav-panel"> <p> Next: <a href="#Arrays-and-matrices" accesskey="n" rel="next">Arrays and matrices</a>, Previous: <a href="#Objects" accesskey="p" rel="prev">Objects, their modes and attributes</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="chapter" id="Ordered-and-unordered-factors"><span>4 Ordered and unordered factors<a class="copiable-link" href="#Ordered-and-unordered-factors"> ¶</a></span></h2> <a class="index-entry-id" id="index-Factors"></a> <a class="index-entry-id" id="index-Ordered-factors"></a> <p>A <em class="emph">factor</em> is a vector object used to specify a discrete classification (grouping) of the components of other vectors of the same length. R provides both <em class="emph">ordered</em> and <em class="emph">unordered</em> factors. While the “real” application of factors is with model formulae (see <a class="pxref" href="#Contrasts">Contrasts</a>), we here look at a specific example. </p> <ul class="mini-toc"> <li><a href="#A-specific-example" accesskey="1">A specific example</a></li> <li><a href="#The-function-tapply_0028_0029-and-ragged-arrays" accesskey="2">The function <code class="code">tapply()</code> and ragged arrays</a></li> <li><a href="#Ordered-factors" accesskey="3">Ordered factors</a></li> </ul> <div class="section-level-extent" id="A-specific-example"> <h3 class="section"><span>4.1 A specific example<a class="copiable-link" href="#A-specific-example"> ¶</a></span></h3> <p>Suppose, for example, we have a sample of 30 tax accountants from all the states and territories of Australia<a class="footnote" id="DOCF14" href="#FOOT14"><sup>14</sup></a> and their individual state of origin is specified by a character vector of state mnemonics as </p> <div class="example"> <pre class="example-preformatted">> state <- c("tas", "sa", "qld", "nsw", "nsw", "nt", "wa", "wa", "qld", "vic", "nsw", "vic", "qld", "qld", "sa", "tas", "sa", "nt", "wa", "vic", "qld", "nsw", "nsw", "wa", "sa", "act", "nsw", "vic", "vic", "act") </pre></div> <p>Notice that in the case of a character vector, “sorted” means sorted in alphabetical order. </p> <p>A <em class="emph">factor</em> is similarly created using the <code class="code">factor()</code> function: <a class="index-entry-id" id="index-factor"></a> </p> <div class="example"> <pre class="example-preformatted">> statef <- factor(state) </pre></div> <p>The <code class="code">print()</code> function handles factors slightly differently from other objects: </p> <div class="example"> <pre class="example-preformatted">> statef [1] tas sa qld nsw nsw nt wa wa qld vic nsw vic qld qld sa [16] tas sa nt wa vic qld nsw nsw wa sa act nsw vic vic act Levels: act nsw nt qld sa tas vic wa </pre></div> <p>To find out the levels of a factor the function <code class="code">levels()</code> can be used. <a class="index-entry-id" id="index-levels"></a> </p> <div class="example"> <pre class="example-preformatted">> levels(statef) [1] "act" "nsw" "nt" "qld" "sa" "tas" "vic" "wa" </pre></div> <hr> </div> <div class="section-level-extent" id="The-function-tapply_0028_0029-and-ragged-arrays"> <div class="nav-panel"> <p> Next: <a href="#Ordered-factors" accesskey="n" rel="next">Ordered factors</a>, Previous: <a href="#Factors" accesskey="p" rel="prev">Ordered and unordered factors</a>, Up: <a href="#Factors" accesskey="u" rel="up">Ordered and unordered factors</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="The-function-tapply_0028_0029-and-ragged-arrays-1"><span>4.2 The function <code class="code">tapply()</code> and ragged arrays<a class="copiable-link" href="#The-function-tapply_0028_0029-and-ragged-arrays-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-tapply"></a> <p>To continue the previous example, suppose we have the incomes of the same tax accountants in another vector (in suitably large units of money) </p> <div class="example"> <pre class="example-preformatted">> incomes <- c(60, 49, 40, 61, 64, 60, 59, 54, 62, 69, 70, 42, 56, 61, 61, 61, 58, 51, 48, 65, 49, 49, 41, 48, 52, 46, 59, 46, 58, 43) </pre></div> <p>To calculate the sample mean income for each state we can now use the special function <code class="code">tapply()</code>: </p> <div class="example"> <pre class="example-preformatted">> incmeans <- tapply(incomes, statef, mean) </pre></div> <p>giving a means vector with the components labelled by the levels </p> <div class="example"> <pre class="example-preformatted"> act nsw nt qld sa tas vic wa 44.500 57.333 55.500 53.600 55.000 60.500 56.000 52.250 </pre></div> <p>The function <code class="code">tapply()</code> is used to apply a function, here <code class="code">mean()</code>, to each group of components of the first argument, here <code class="code">incomes</code>, defined by the levels of the second component, here <code class="code">statef</code><a class="footnote" id="DOCF15" href="#FOOT15"><sup>15</sup></a>, as if they were separate vector structures. The result is a structure of the same length as the levels attribute of the factor containing the results. The reader should consult the help document for more details. </p> <p>Suppose further we needed to calculate the standard errors of the state income means. To do this we need to write an R function to calculate the standard error for any given vector. Since there is an builtin function <code class="code">var()</code> to calculate the sample variance, such a function is a very simple one liner, specified by the assignment: </p> <div class="example"> <pre class="example-preformatted">> stdError <- function(x) sqrt(var(x)/length(x)) </pre></div> <p>(Writing functions will be considered later in <a class="ref" href="#Writing-your-own-functions">Writing your own functions</a>. Note that R’s a builtin function <code class="code">sd()</code> is something different.) <a class="index-entry-id" id="index-sd"></a> <a class="index-entry-id" id="index-var-1"></a> After this assignment, the standard errors are calculated by </p> <div class="example"> <pre class="example-preformatted">> incster <- tapply(incomes, statef, stdError) </pre></div> <p>and the values calculated are then </p> <div class="example"> <pre class="example-preformatted">> incster act nsw nt qld sa tas vic wa 1.5 4.3102 4.5 4.1061 2.7386 0.5 5.244 2.6575 </pre></div> <p>As an exercise you may care to find the usual 95% confidence limits for the state mean incomes. To do this you could use <code class="code">tapply()</code> once more with the <code class="code">length()</code> function to find the sample sizes, and the <code class="code">qt()</code> function to find the percentage points of the appropriate <em class="math">t</em>-distributions. (You could also investigate R’s facilities for <em class="math">t</em>-tests.) </p> <p>The function <code class="code">tapply()</code> can also be used to handle more complicated indexing of a vector by multiple categories. For example, we might wish to split the tax accountants by both state and sex. However in this simple instance (just one factor) what happens can be thought of as follows. The values in the vector are collected into groups corresponding to the distinct entries in the factor. The function is then applied to each of these groups individually. The value is a vector of function results, labelled by the <code class="code">levels</code> attribute of the factor. </p> <p>The combination of a vector and a labelling factor is an example of what is sometimes called a <em class="emph">ragged array</em>, since the subclass sizes are possibly irregular. When the subclass sizes are all the same the indexing may be done implicitly and much more efficiently, as we see in the next section. </p> <hr> </div> <div class="section-level-extent" id="Ordered-factors"> <div class="nav-panel"> <p> Previous: <a href="#The-function-tapply_0028_0029-and-ragged-arrays" accesskey="p" rel="prev">The function <code class="code">tapply()</code> and ragged arrays</a>, Up: <a href="#Factors" accesskey="u" rel="up">Ordered and unordered factors</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Ordered-factors-1"><span>4.3 Ordered factors<a class="copiable-link" href="#Ordered-factors-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-ordered"></a> <p>The levels of factors are stored in alphabetical order, or in the order they were specified to <code class="code">factor</code> if they were specified explicitly. </p> <p>Sometimes the levels will have a natural ordering that we want to record and want our statistical analysis to make use of. The <code class="code">ordered()</code> <a class="index-entry-id" id="index-ordered-1"></a> function creates such ordered factors but is otherwise identical to <code class="code">factor</code>. For most purposes the only difference between ordered and unordered factors is that the former are printed showing the ordering of the levels, but the contrasts generated for them in fitting linear models are different. </p> <hr> </div> </div> <div class="chapter-level-extent" id="Arrays-and-matrices"> <div class="nav-panel"> <p> Next: <a href="#Lists-and-data-frames" accesskey="n" rel="next">Lists and data frames</a>, Previous: <a href="#Factors" accesskey="p" rel="prev">Ordered and unordered factors</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="chapter" id="Arrays-and-matrices-1"><span>5 Arrays and matrices<a class="copiable-link" href="#Arrays-and-matrices-1"> ¶</a></span></h2> <ul class="mini-toc"> <li><a href="#Arrays" accesskey="1">Arrays</a></li> <li><a href="#Array-indexing" accesskey="2">Array indexing. Subsections of an array</a></li> <li><a href="#Index-matrices" accesskey="3">Index matrices</a></li> <li><a href="#The-array_0028_0029-function" accesskey="4">The <code class="code">array()</code> function</a></li> <li><a href="#The-outer-product-of-two-arrays" accesskey="5">The outer product of two arrays</a></li> <li><a href="#Generalized-transpose-of-an-array" accesskey="6">Generalized transpose of an array</a></li> <li><a href="#Matrix-facilities" accesskey="7">Matrix facilities</a></li> <li><a href="#Forming-partitioned-matrices" accesskey="8">Forming partitioned matrices, <code class="code">cbind()</code> and <code class="code">rbind()</code></a></li> <li><a href="#The-concatenation-function-c_0028_0029-with-arrays" accesskey="9">The concatenation function, <code class="code">c()</code>, with arrays</a></li> <li><a href="#Frequency-tables-from-factors">Frequency tables from factors</a></li> </ul> <hr> <div class="section-level-extent" id="Arrays"> <div class="nav-panel"> <p> Next: <a href="#Array-indexing" accesskey="n" rel="next">Array indexing. Subsections of an array</a>, Previous: <a href="#Arrays-and-matrices" accesskey="p" rel="prev">Arrays and matrices</a>, Up: <a href="#Arrays-and-matrices" accesskey="u" rel="up">Arrays and matrices</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Arrays-1"><span>5.1 Arrays<a class="copiable-link" href="#Arrays-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Arrays"></a> <a class="index-entry-id" id="index-Matrices"></a> <p>An array can be considered as a multiply subscripted collection of data entries, for example numeric. R allows simple facilities for creating and handling arrays, and in particular the special case of matrices. </p> <p>A dimension vector is a vector of non-negative integers. If its length is <em class="math">k</em> then the array is <em class="math">k</em>-dimensional, e.g. a matrix is a <em class="math">2</em>-dimensional array. The dimensions are indexed from one up to the values given in the dimension vector. </p> <p>A vector can be used by R as an array only if it has a dimension vector as its <em class="emph">dim</em> attribute. Suppose, for example, <code class="code">z</code> is a vector of 1500 elements. The assignment </p> <div class="example"> <pre class="example-preformatted">> dim(z) <- c(3,5,100) </pre></div> <a class="index-entry-id" id="index-dim"></a> <p>gives it the <em class="emph">dim</em> attribute that allows it to be treated as a <em class="math">3</em> by <em class="math">5</em> by <em class="math">100</em> array. </p> <p>Other functions such as <code class="code">matrix()</code> and <code class="code">array()</code> are available for simpler and more natural looking assignments, as we shall see in <a class="ref" href="#The-array_0028_0029-function">The <code class="code">array()</code> function</a>. </p> <p>The values in the data vector give the values in the array in the same order as they would occur in FORTRAN, that is “column major order,” with the first subscript moving fastest and the last subscript slowest. </p> <p>For example if the dimension vector for an array, say <code class="code">a</code>, is <code class="code">c(3,4,2)</code> then there are 3 * 4 * 2 = 24 entries in <code class="code">a</code> and the data vector holds them in the order <code class="code">a[1,1,1], a[2,1,1], …, a[2,4,2], a[3,4,2]</code>. </p> <p>Arrays can be one-dimensional: such arrays are usually treated in the same way as vectors (including when printing), but the exceptions can cause confusion. </p> <hr> </div> <div class="section-level-extent" id="Array-indexing"> <div class="nav-panel"> <p> Next: <a href="#Index-matrices" accesskey="n" rel="next">Index matrices</a>, Previous: <a href="#Arrays" accesskey="p" rel="prev">Arrays</a>, Up: <a href="#Arrays-and-matrices" accesskey="u" rel="up">Arrays and matrices</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Array-indexing_002e-Subsections-of-an-array"><span>5.2 Array indexing. Subsections of an array<a class="copiable-link" href="#Array-indexing_002e-Subsections-of-an-array"> ¶</a></span></h3> <a class="index-entry-id" id="index-Indexing-of-and-by-arrays"></a> <p>Individual elements of an array may be referenced by giving the name of the array followed by the subscripts in square brackets, separated by commas. </p> <p>More generally, subsections of an array may be specified by giving a sequence of <em class="emph">index vectors</em> in place of subscripts; however <em class="emph">if any index position is given an empty index vector, then the full range of that subscript is taken</em>. </p> <p>Continuing the previous example, <code class="code">a[2,,]</code> is a 4 * 2 array with dimension vector <code class="code">c(4,2)</code> and data vector containing the values </p> <div class="example"> <pre class="example-preformatted">c(a[2,1,1], a[2,2,1], a[2,3,1], a[2,4,1], a[2,1,2], a[2,2,2], a[2,3,2], a[2,4,2]) </pre></div> <p>in that order. <code class="code">a[,,]</code> stands for the entire array, which is the same as omitting the subscripts entirely and using <code class="code">a</code> alone. </p> <p>For any array, say <code class="code">Z</code>, the dimension vector may be referenced explicitly as <code class="code">dim(Z)</code> (on either side of an assignment). </p> <p>Also, if an array name is given with just <em class="emph">one subscript or index vector</em>, then the corresponding values of the data vector only are used; in this case the dimension vector is ignored. This is not the case, however, if the single index is not a vector but itself an array, as we next discuss. </p> <hr> </div> <div class="section-level-extent" id="Index-matrices"> <div class="nav-panel"> <p> Next: <a href="#The-array_0028_0029-function" accesskey="n" rel="next">The <code class="code">array()</code> function</a>, Previous: <a href="#Array-indexing" accesskey="p" rel="prev">Array indexing. Subsections of an array</a>, Up: <a href="#Arrays-and-matrices" accesskey="u" rel="up">Arrays and matrices</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Index-matrices-1"><span>5.3 Index matrices<a class="copiable-link" href="#Index-matrices-1"> ¶</a></span></h3> <p>As well as an index vector in any subscript position, a matrix may be used with a single <em class="emph">index matrix</em> in order either to assign a vector of quantities to an irregular collection of elements in the array, or to extract an irregular collection as a vector. </p> <p>A matrix example makes the process clear. In the case of a doubly indexed array, an index matrix may be given consisting of two columns and as many rows as desired. The entries in the index matrix are the row and column indices for the doubly indexed array. Suppose for example we have a <em class="math">4</em> by <em class="math">5</em> array <code class="code">X</code> and we wish to do the following: </p> <ul class="itemize mark-bullet"> <li>Extract elements <code class="code">X[1,3]</code>, <code class="code">X[2,2]</code> and <code class="code">X[3,1]</code> as a vector structure, and </li><li>Replace these entries in the array <code class="code">X</code> by zeroes. </li></ul> <p>In this case we need a <em class="math">3</em> by <em class="math">2</em> subscript array, as in the following example. </p> <div class="example"> <pre class="example-preformatted">> x <- array(1:20, dim=c(4,5)) # <span class="r">Generate a 4 by 5 array.</span> > x [,1] [,2] [,3] [,4] [,5] [1,] 1 5 9 13 17 [2,] 2 6 10 14 18 [3,] 3 7 11 15 19 [4,] 4 8 12 16 20 > i <- array(c(1:3,3:1), dim=c(3,2)) > i # <span class="r"><code class="code">i</code> is a 3 by 2 index array.</span> [,1] [,2] [1,] 1 3 [2,] 2 2 [3,] 3 1 > x[i] # <span class="r">Extract those elements</span> [1] 9 6 3 > x[i] <- 0 # <span class="r">Replace those elements by zeros.</span> > x [,1] [,2] [,3] [,4] [,5] [1,] 1 5 0 13 17 [2,] 2 0 10 14 18 [3,] 0 7 11 15 19 [4,] 4 8 12 16 20 > </pre></div> <p>Negative indices are not allowed in index matrices. <code class="code">NA</code> and zero values are allowed: rows in the index matrix containing a zero are ignored, and rows containing an <code class="code">NA</code> produce an <code class="code">NA</code> in the result. </p> <p>As a less trivial example, suppose we wish to generate an (unreduced) design matrix for a block design defined by factors <code class="code">blocks</code> (<code class="code">b</code> levels) and <code class="code">varieties</code> (<code class="code">v</code> levels). Further suppose there are <code class="code">n</code> plots in the experiment. We could proceed as follows: </p> <div class="example"> <pre class="example-preformatted">> Xb <- matrix(0, n, b) > Xv <- matrix(0, n, v) > ib <- cbind(1:n, blocks) > iv <- cbind(1:n, varieties) > Xb[ib] <- 1 > Xv[iv] <- 1 > X <- cbind(Xb, Xv) </pre></div> <p>To construct the incidence matrix, <code class="code">N</code> say, we could use </p> <div class="example"> <pre class="example-preformatted">> N <- crossprod(Xb, Xv) </pre></div> <a class="index-entry-id" id="index-crossprod"></a> <p>However a simpler direct way of producing this matrix is to use <code class="code">table()</code>: <a class="index-entry-id" id="index-table"></a> </p> <div class="example"> <pre class="example-preformatted">> N <- table(blocks, varieties) </pre></div> <p>Index matrices must be numerical: any other form of matrix (e.g. a logical or character matrix) supplied as a matrix is treated as an indexing vector. </p> <hr> </div> <div class="section-level-extent" id="The-array_0028_0029-function"> <div class="nav-panel"> <p> Next: <a href="#The-outer-product-of-two-arrays" accesskey="n" rel="next">The outer product of two arrays</a>, Previous: <a href="#Index-matrices" accesskey="p" rel="prev">Index matrices</a>, Up: <a href="#Arrays-and-matrices" accesskey="u" rel="up">Arrays and matrices</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="The-array_0028_0029-function-1"><span>5.4 The <code class="code">array()</code> function<a class="copiable-link" href="#The-array_0028_0029-function-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-array"></a> <p>As well as giving a vector structure a <code class="code">dim</code> attribute, arrays can be constructed from vectors by the <code class="code">array</code> function, which has the form </p> <div class="example"> <pre class="example-preformatted">> Z <- array(<var class="var">data_vector</var>, <var class="var">dim_vector</var>) </pre></div> <p>For example, if the vector <code class="code">h</code> contains 24 or fewer, numbers then the command </p> <div class="example"> <pre class="example-preformatted">> Z <- array(h, dim=c(3,4,2)) </pre></div> <p>would use <code class="code">h</code> to set up <em class="math">3</em> by <em class="math">4</em> by <em class="math">2</em> array in <code class="code">Z</code>. If the size of <code class="code">h</code> is exactly 24 the result is the same as </p> <div class="example"> <pre class="example-preformatted">> Z <- h ; dim(Z) <- c(3,4,2) </pre></div> <p>However if <code class="code">h</code> is shorter than 24, its values are recycled from the beginning again to make it up to size 24 (see <a class="pxref" href="#The-recycling-rule">Mixed vector and array arithmetic. The recycling rule</a>) but <code class="code">dim(h) <- c(3,4,2)</code> would signal an error about mismatching length. As an extreme but common example </p> <div class="example"> <pre class="example-preformatted">> Z <- array(0, c(3,4,2)) </pre></div> <p>makes <code class="code">Z</code> an array of all zeros. </p> <p>At this point <code class="code">dim(Z)</code> stands for the dimension vector <code class="code">c(3,4,2)</code>, and <code class="code">Z[1:24]</code> stands for the data vector as it was in <code class="code">h</code>, and <code class="code">Z[]</code> with an empty subscript or <code class="code">Z</code> with no subscript stands for the entire array as an array. </p> <p>Arrays may be used in arithmetic expressions and the result is an array formed by element-by-element operations on the data vector. The <code class="code">dim</code> attributes of operands generally need to be the same, and this becomes the dimension vector of the result. So if <code class="code">A</code>, <code class="code">B</code> and <code class="code">C</code> are all similar arrays, then </p> <div class="example"> <pre class="example-preformatted">> D <- 2*A*B + C + 1 </pre></div> <p>makes <code class="code">D</code> a similar array with its data vector being the result of the given element-by-element operations. However the precise rule concerning mixed array and vector calculations has to be considered a little more carefully. </p> <ul class="mini-toc"> <li><a href="#The-recycling-rule" accesskey="1">Mixed vector and array arithmetic. The recycling rule</a></li> </ul> <hr> <div class="subsection-level-extent" id="The-recycling-rule"> <div class="nav-panel"> <p> Previous: <a href="#The-array_0028_0029-function" accesskey="p" rel="prev">The <code class="code">array()</code> function</a>, Up: <a href="#The-array_0028_0029-function" accesskey="u" rel="up">The <code class="code">array()</code> function</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Mixed-vector-and-array-arithmetic_002e-The-recycling-rule"><span>5.4.1 Mixed vector and array arithmetic. The recycling rule<a class="copiable-link" href="#Mixed-vector-and-array-arithmetic_002e-The-recycling-rule"> ¶</a></span></h4> <a class="index-entry-id" id="index-Recycling-rule-1"></a> <p>The precise rule affecting element by element mixed calculations with vectors and arrays is somewhat quirky and hard to find in the references. From experience we have found the following to be a reliable guide. </p> <ul class="itemize mark-bullet"> <li>The expression is scanned from left to right. </li><li>Any short vector operands are extended by recycling their values until they match the size of any other operands. </li><li>As long as short vectors and arrays <em class="emph">only</em> are encountered, the arrays must all have the same <code class="code">dim</code> attribute or an error results. </li><li>Any vector operand longer than a matrix or array operand generates an error. </li><li>If array structures are present and no error or coercion to vector has been precipitated, the result is an array structure with the common <code class="code">dim</code> attribute of its array operands. </li></ul> <hr> </div> </div> <div class="section-level-extent" id="The-outer-product-of-two-arrays"> <div class="nav-panel"> <p> Next: <a href="#Generalized-transpose-of-an-array" accesskey="n" rel="next">Generalized transpose of an array</a>, Previous: <a href="#The-array_0028_0029-function" accesskey="p" rel="prev">The <code class="code">array()</code> function</a>, Up: <a href="#Arrays-and-matrices" accesskey="u" rel="up">Arrays and matrices</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="The-outer-product-of-two-arrays-1"><span>5.5 The outer product of two arrays<a class="copiable-link" href="#The-outer-product-of-two-arrays-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Outer-products-of-arrays"></a> <p>An important operation on arrays is the <em class="emph">outer product</em>. If <code class="code">a</code> and <code class="code">b</code> are two numeric arrays, their outer product is an array whose dimension vector is obtained by concatenating their two dimension vectors (order is important), and whose data vector is got by forming all possible products of elements of the data vector of <code class="code">a</code> with those of <code class="code">b</code>. The outer product is formed by the special operator <code class="code">%o%</code>: <a class="index-entry-id" id="index-_0025o_0025"></a> </p> <div class="example"> <pre class="example-preformatted">> ab <- a %o% b </pre></div> <p>An alternative is </p> <div class="example"> <pre class="example-preformatted">> ab <- outer(a, b, "*") </pre></div> <a class="index-entry-id" id="index-outer"></a> <p>The multiplication function can be replaced by an arbitrary function of two variables. For example if we wished to evaluate the function f(x; y) = cos(y)/(1 + x^2) over a regular grid of values with <em class="math">x</em>- and <em class="math">y</em>-coordinates defined by the R vectors <code class="code">x</code> and <code class="code">y</code> respectively, we could proceed as follows: </p> <div class="example"> <pre class="example-preformatted">> f <- function(x, y) cos(y)/(1 + x^2) > z <- outer(x, y, f) </pre></div> <p>In particular the outer product of two ordinary vectors is a doubly subscripted array (that is a matrix, of rank at most 1). Notice that the outer product operator is of course non-commutative. Defining your own R functions will be considered further in <a class="ref" href="#Writing-your-own-functions">Writing your own functions</a>. </p> <h4 class="subsubheading" id="An-example_003a-Determinants-of-2-by-2-single_002ddigit-matrices"><span>An example: Determinants of 2 by 2 single-digit matrices<a class="copiable-link" href="#An-example_003a-Determinants-of-2-by-2-single_002ddigit-matrices"> ¶</a></span></h4> <p>As an artificial but cute example, consider the determinants of <em class="math">2</em> by <em class="math">2</em> matrices <em class="math">[a, b; c, d]</em> where each entry is a non-negative integer in the range <em class="math">0, 1, ..., 9</em>, that is a digit. </p> <p>The problem is to find the determinants, <em class="math">ad - bc</em>, of all possible matrices of this form and represent the frequency with which each value occurs as a <em class="emph">high density</em> plot. This amounts to finding the probability distribution of the determinant if each digit is chosen independently and uniformly at random. </p> <p>A neat way of doing this uses the <code class="code">outer()</code> function twice: </p> <div class="example"> <pre class="example-preformatted">> d <- outer(0:9, 0:9) > fr <- table(outer(d, d, "-")) > plot(fr, xlab="Determinant", ylab="Frequency") </pre></div> <p>Notice that <code class="code">plot()</code> here uses a histogram like plot method, because it “sees” that <code class="code">fr</code> is of class <code class="code">"table"</code>. The “obvious” way of doing this problem with <code class="code">for</code> loops, to be discussed in <a class="ref" href="#Loops-and-conditional-execution">Grouping, loops and conditional execution</a>, is so inefficient as to be impractical. </p> <p>It is also perhaps surprising that about 1 in 20 such matrices is singular. </p> <hr> </div> <div class="section-level-extent" id="Generalized-transpose-of-an-array"> <div class="nav-panel"> <p> Next: <a href="#Matrix-facilities" accesskey="n" rel="next">Matrix facilities</a>, Previous: <a href="#The-outer-product-of-two-arrays" accesskey="p" rel="prev">The outer product of two arrays</a>, Up: <a href="#Arrays-and-matrices" accesskey="u" rel="up">Arrays and matrices</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Generalized-transpose-of-an-array-1"><span>5.6 Generalized transpose of an array<a class="copiable-link" href="#Generalized-transpose-of-an-array-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Generalized-transpose-of-an-array"></a> <p>The function <code class="code">aperm(a, perm)</code> <a class="index-entry-id" id="index-aperm"></a> may be used to permute an array, <code class="code">a</code>. The argument <code class="code">perm</code> must be a permutation of the integers <em class="math">{1, ..., k}</em>, where <em class="math">k</em> is the number of subscripts in <code class="code">a</code>. The result of the function is an array of the same size as <code class="code">a</code> but with old dimension given by <code class="code">perm[j]</code> becoming the new <code class="code">j</code>-th dimension. The easiest way to think of this operation is as a generalization of transposition for matrices. Indeed if <code class="code">A</code> is a matrix, (that is, a doubly subscripted array) then <code class="code">B</code> given by </p> <div class="example"> <pre class="example-preformatted">> B <- aperm(A, c(2,1)) </pre></div> <p>is just the transpose of <code class="code">A</code>. For this special case a simpler function <code class="code">t()</code> <a class="index-entry-id" id="index-t"></a> is available, so we could have used <code class="code">B <- t(A)</code>. </p> <hr> </div> <div class="section-level-extent" id="Matrix-facilities"> <div class="nav-panel"> <p> Next: <a href="#Forming-partitioned-matrices" accesskey="n" rel="next">Forming partitioned matrices, <code class="code">cbind()</code> and <code class="code">rbind()</code></a>, Previous: <a href="#Generalized-transpose-of-an-array" accesskey="p" rel="prev">Generalized transpose of an array</a>, Up: <a href="#Arrays-and-matrices" accesskey="u" rel="up">Arrays and matrices</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Matrix-facilities-1"><span>5.7 Matrix facilities<a class="copiable-link" href="#Matrix-facilities-1"> ¶</a></span></h3> <p>As noted above, a matrix is just an array with two subscripts. However it is such an important special case it needs a separate discussion. R contains many operators and functions that are available only for matrices. For example <code class="code">t(X)</code> is the matrix transpose function, as noted above. The functions <code class="code">nrow(A)</code> and <code class="code">ncol(A)</code> give the number of rows and columns in the matrix <code class="code">A</code> respectively. <a class="index-entry-id" id="index-nrow"></a> <a class="index-entry-id" id="index-ncol"></a> </p> <ul class="mini-toc"> <li><a href="#Multiplication" accesskey="1">Matrix multiplication</a></li> <li><a href="#Linear-equations-and-inversion" accesskey="2">Linear equations and inversion</a></li> <li><a href="#Eigenvalues-and-eigenvectors" accesskey="3">Eigenvalues and eigenvectors</a></li> <li><a href="#Singular-value-decomposition-and-determinants" accesskey="4">Singular value decomposition and determinants</a></li> <li><a href="#Least-squares-fitting-and-the-QR-decomposition" accesskey="5">Least squares fitting and the QR decomposition</a></li> </ul> <hr> <div class="subsection-level-extent" id="Multiplication"> <div class="nav-panel"> <p> Next: <a href="#Linear-equations-and-inversion" accesskey="n" rel="next">Linear equations and inversion</a>, Previous: <a href="#Matrix-facilities" accesskey="p" rel="prev">Matrix facilities</a>, Up: <a href="#Matrix-facilities" accesskey="u" rel="up">Matrix facilities</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Matrix-multiplication"><span>5.7.1 Matrix multiplication<a class="copiable-link" href="#Matrix-multiplication"> ¶</a></span></h4> <a class="index-entry-id" id="index-Matrix-multiplication"></a> <p>The operator <code class="code">%*%</code> is used for matrix multiplication. <a class="index-entry-id" id="index-_0025_002a_0025"></a> An <em class="math">n</em> by <em class="math">1</em> or <em class="math">1</em> by <em class="math">n</em> matrix may of course be used as an <em class="math">n</em>-vector if in the context such is appropriate. Conversely, vectors which occur in matrix multiplication expressions are automatically promoted either to row or column vectors, whichever is multiplicatively coherent, if possible, (although this is not always unambiguously possible, as we see later). </p> <p>If, for example, <code class="code">A</code> and <code class="code">B</code> are square matrices of the same size, then </p> <div class="example"> <pre class="example-preformatted">> A * B </pre></div> <p>is the matrix of element by element products and </p> <div class="example"> <pre class="example-preformatted">> A %*% B </pre></div> <p>is the matrix product. If <code class="code">x</code> is a vector, then </p> <div class="example"> <pre class="example-preformatted">> x %*% A %*% x </pre></div> <p>is a quadratic form.<a class="footnote" id="DOCF16" href="#FOOT16"><sup>16</sup></a> </p> <a class="index-entry-id" id="index-crossprod-1"></a> <p>The function <code class="code">crossprod()</code> forms “cross products”, meaning that <code class="code">crossprod(X, y)</code> is the same as <code class="code">t(X) %*% y</code> but the operation is more efficient. If the second argument to <code class="code">crossprod()</code> is omitted it is taken to be the same as the first. </p> <a class="index-entry-id" id="index-diag"></a> <p>The meaning of <code class="code">diag()</code> depends on its argument. <code class="code">diag(v)</code>, where <code class="code">v</code> is a vector, gives a diagonal matrix with elements of the vector as the diagonal entries. On the other hand <code class="code">diag(M)</code>, where <code class="code">M</code> is a matrix, gives the vector of main diagonal entries of <code class="code">M</code>. This is the same convention as that used for <code class="code">diag()</code> in <small class="sc">MATLAB</small>. Also, somewhat confusingly, if <code class="code">k</code> is a single numeric value then <code class="code">diag(k)</code> is the <code class="code">k</code> by <code class="code">k</code> identity matrix! </p> <hr> </div> <div class="subsection-level-extent" id="Linear-equations-and-inversion"> <div class="nav-panel"> <p> Next: <a href="#Eigenvalues-and-eigenvectors" accesskey="n" rel="next">Eigenvalues and eigenvectors</a>, Previous: <a href="#Multiplication" accesskey="p" rel="prev">Matrix multiplication</a>, Up: <a href="#Matrix-facilities" accesskey="u" rel="up">Matrix facilities</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Linear-equations-and-inversion-1"><span>5.7.2 Linear equations and inversion<a class="copiable-link" href="#Linear-equations-and-inversion-1"> ¶</a></span></h4> <a class="index-entry-id" id="index-Linear-equations"></a> <a class="index-entry-id" id="index-solve"></a> <p>Solving linear equations is the inverse of matrix multiplication. When after </p> <div class="example"> <pre class="example-preformatted">> b <- A %*% x </pre></div> <p>only <code class="code">A</code> and <code class="code">b</code> are given, the vector <code class="code">x</code> is the solution of that linear equation system. In R, </p> <div class="example"> <pre class="example-preformatted">> solve(A,b) </pre></div> <p>solves the system, returning <code class="code">x</code> (up to some accuracy loss). Note that in linear algebra, formally <code class="code">x = A^{-1} %*% b</code> where <code class="code">A^{-1}</code> denotes the <em class="emph">inverse</em> of <code class="code">A</code>, which can be computed by </p> <div class="example"> <pre class="example-preformatted">solve(A) </pre></div> <p>but rarely is needed. Numerically, it is both inefficient and potentially unstable to compute <code class="code">x <- solve(A) %*% b</code> instead of <code class="code">solve(A,b)</code>. </p> <p>The quadratic form <code class="code">x %*% A^{-1} %*% x</code> which is used in multivariate computations, should be computed by something like<a class="footnote" id="DOCF17" href="#FOOT17"><sup>17</sup></a> <code class="code">x %*% solve(A,x)</code>, rather than computing the inverse of <code class="code">A</code>. </p> <hr> </div> <div class="subsection-level-extent" id="Eigenvalues-and-eigenvectors"> <div class="nav-panel"> <p> Next: <a href="#Singular-value-decomposition-and-determinants" accesskey="n" rel="next">Singular value decomposition and determinants</a>, Previous: <a href="#Linear-equations-and-inversion" accesskey="p" rel="prev">Linear equations and inversion</a>, Up: <a href="#Matrix-facilities" accesskey="u" rel="up">Matrix facilities</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Eigenvalues-and-eigenvectors-1"><span>5.7.3 Eigenvalues and eigenvectors<a class="copiable-link" href="#Eigenvalues-and-eigenvectors-1"> ¶</a></span></h4> <a class="index-entry-id" id="index-Eigenvalues-and-eigenvectors"></a> <a class="index-entry-id" id="index-eigen"></a> <p>The function <code class="code">eigen(Sm)</code> calculates the eigenvalues and eigenvectors of a symmetric matrix <code class="code">Sm</code>. The result of this function is a list of two components named <code class="code">values</code> and <code class="code">vectors</code>. The assignment </p> <div class="example"> <pre class="example-preformatted">> ev <- eigen(Sm) </pre></div> <p>will assign this list to <code class="code">ev</code>. Then <code class="code">ev$val</code> is the vector of eigenvalues of <code class="code">Sm</code> and <code class="code">ev$vec</code> is the matrix of corresponding eigenvectors. Had we only needed the eigenvalues we could have used the assignment: </p> <div class="example"> <pre class="example-preformatted">> evals <- eigen(Sm)$values </pre></div> <p><code class="code">evals</code> now holds the vector of eigenvalues and the second component is discarded. If the expression </p> <div class="example"> <pre class="example-preformatted">> eigen(Sm) </pre></div> <p>is used by itself as a command the two components are printed, with their names. For large matrices it is better to avoid computing the eigenvectors if they are not needed by using the expression </p> <div class="example"> <pre class="example-preformatted">> evals <- eigen(Sm, only.values = TRUE)$values </pre></div> <hr> </div> <div class="subsection-level-extent" id="Singular-value-decomposition-and-determinants"> <div class="nav-panel"> <p> Next: <a href="#Least-squares-fitting-and-the-QR-decomposition" accesskey="n" rel="next">Least squares fitting and the QR decomposition</a>, Previous: <a href="#Eigenvalues-and-eigenvectors" accesskey="p" rel="prev">Eigenvalues and eigenvectors</a>, Up: <a href="#Matrix-facilities" accesskey="u" rel="up">Matrix facilities</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Singular-value-decomposition-and-determinants-1"><span>5.7.4 Singular value decomposition and determinants<a class="copiable-link" href="#Singular-value-decomposition-and-determinants-1"> ¶</a></span></h4> <a class="index-entry-id" id="index-Singular-value-decomposition"></a> <a class="index-entry-id" id="index-svd"></a> <p>The function <code class="code">svd(M)</code> takes an arbitrary matrix argument, <code class="code">M</code>, and calculates the singular value decomposition of <code class="code">M</code>. This consists of a matrix of orthonormal columns <code class="code">U</code> with the same column space as <code class="code">M</code>, a second matrix of orthonormal columns <code class="code">V</code> whose column space is the row space of <code class="code">M</code> and a diagonal matrix of positive entries <code class="code">D</code> such that <code class="code">M = U %*% D %*% t(V)</code>. <code class="code">D</code> is actually returned as a vector of the diagonal elements. The result of <code class="code">svd(M)</code> is actually a list of three components named <code class="code">d</code>, <code class="code">u</code> and <code class="code">v</code>, with evident meanings. </p> <p>If <code class="code">M</code> is in fact square, then, it is not hard to see that </p> <div class="example"> <pre class="example-preformatted">> absdetM <- prod(svd(M)$d) </pre></div> <p>calculates the absolute value of the determinant of <code class="code">M</code>. If this calculation were needed often with a variety of matrices it could be defined as an R function </p> <div class="example"> <pre class="example-preformatted">> absdet <- function(M) prod(svd(M)$d) </pre></div> <a class="index-entry-id" id="index-Determinants"></a> <p>after which we could use <code class="code">absdet()</code> as just another R function. As a further trivial but potentially useful example, you might like to consider writing a function, say <code class="code">tr()</code>, to calculate the trace of a square matrix. [Hint: You will not need to use an explicit loop. Look again at the <code class="code">diag()</code> function.] </p> <a class="index-entry-id" id="index-det"></a> <a class="index-entry-id" id="index-determinant"></a> <p>R has a builtin function <code class="code">det</code> to calculate a determinant, including the sign, and another, <code class="code">determinant</code>, to give the sign and modulus (optionally on log scale), </p> <hr> </div> <div class="subsection-level-extent" id="Least-squares-fitting-and-the-QR-decomposition"> <div class="nav-panel"> <p> Previous: <a href="#Singular-value-decomposition-and-determinants" accesskey="p" rel="prev">Singular value decomposition and determinants</a>, Up: <a href="#Matrix-facilities" accesskey="u" rel="up">Matrix facilities</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Least-squares-fitting-and-the-QR-decomposition-1"><span>5.7.5 Least squares fitting and the QR decomposition<a class="copiable-link" href="#Least-squares-fitting-and-the-QR-decomposition-1"> ¶</a></span></h4> <a class="index-entry-id" id="index-Least-squares-fitting"></a> <a class="index-entry-id" id="index-QR-decomposition"></a> <p>The function <code class="code">lsfit()</code> returns a list giving results of a least squares fitting procedure. An assignment such as </p> <div class="example"> <pre class="example-preformatted">> ans <- lsfit(X, y) </pre></div> <a class="index-entry-id" id="index-lsfit"></a> <p>gives the results of a least squares fit where <code class="code">y</code> is the vector of observations and <code class="code">X</code> is the design matrix. See the help facility for more details, and also for the follow-up function <code class="code">ls.diag()</code> for, among other things, regression diagnostics. Note that a grand mean term is automatically included and need not be included explicitly as a column of <code class="code">X</code>. Further note that you almost always will prefer using <code class="code">lm(.)</code> (see <a class="pxref" href="#Linear-models">Linear models</a>) to <code class="code">lsfit()</code> for regression modelling. </p> <a class="index-entry-id" id="index-qr"></a> <p>Another closely related function is <code class="code">qr()</code> and its allies. Consider the following assignments </p> <div class="example"> <pre class="example-preformatted">> Xplus <- qr(X) > b <- qr.coef(Xplus, y) > fit <- qr.fitted(Xplus, y) > res <- qr.resid(Xplus, y) </pre></div> <p>These compute the orthogonal projection of <code class="code">y</code> onto the range of <code class="code">X</code> in <code class="code">fit</code>, the projection onto the orthogonal complement in <code class="code">res</code> and the coefficient vector for the projection in <code class="code">b</code>, that is, <code class="code">b</code> is essentially the result of the <small class="sc">MATLAB</small> ‘backslash’ operator. </p> <p>It is not assumed that <code class="code">X</code> has full column rank. Redundancies will be discovered and removed as they are found. </p> <p>This alternative is the older, low-level way to perform least squares calculations. Although still useful in some contexts, it would now generally be replaced by the statistical models features, as will be discussed in <a class="ref" href="#Statistical-models-in-R">Statistical models in R</a>. </p> <hr> </div> </div> <div class="section-level-extent" id="Forming-partitioned-matrices"> <div class="nav-panel"> <p> Next: <a href="#The-concatenation-function-c_0028_0029-with-arrays" accesskey="n" rel="next">The concatenation function, <code class="code">c()</code>, with arrays</a>, Previous: <a href="#Matrix-facilities" accesskey="p" rel="prev">Matrix facilities</a>, Up: <a href="#Arrays-and-matrices" accesskey="u" rel="up">Arrays and matrices</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Forming-partitioned-matrices_002c-cbind_0028_0029-and-rbind_0028_0029"><span>5.8 Forming partitioned matrices, <code class="code">cbind()</code> and <code class="code">rbind()</code><a class="copiable-link" href="#Forming-partitioned-matrices_002c-cbind_0028_0029-and-rbind_0028_0029"> ¶</a></span></h3> <a class="index-entry-id" id="index-cbind"></a> <a class="index-entry-id" id="index-rbind"></a> <p>As we have already seen informally, matrices can be built up from other vectors and matrices by the functions <code class="code">cbind()</code> and <code class="code">rbind()</code>. Roughly <code class="code">cbind()</code> forms matrices by binding together matrices horizontally, or column-wise, and <code class="code">rbind()</code> vertically, or row-wise. </p> <p>In the assignment </p> <div class="example"> <pre class="example-preformatted">> X <- cbind(<var class="var">arg_1</var>, <var class="var">arg_2</var>, <var class="var">arg_3</var>, ...) </pre></div> <p>the arguments to <code class="code">cbind()</code> must be either vectors of any length, or matrices with the same column size, that is the same number of rows. The result is a matrix with the concatenated arguments <var class="var">arg_1</var>, <var class="var">arg_2</var>, … forming the columns. </p> <p>If some of the arguments to <code class="code">cbind()</code> are vectors they may be shorter than the column size of any matrices present, in which case they are cyclically extended to match the matrix column size (or the length of the longest vector if no matrices are given). </p> <p>The function <code class="code">rbind()</code> does the corresponding operation for rows. In this case any vector argument, possibly cyclically extended, are of course taken as row vectors. </p> <p>Suppose <code class="code">X1</code> and <code class="code">X2</code> have the same number of rows. To combine these by columns into a matrix <code class="code">X</code>, together with an initial column of <code class="code">1</code>s we can use </p> <div class="example"> <pre class="example-preformatted">> X <- cbind(1, X1, X2) </pre></div> <p>The result of <code class="code">rbind()</code> or <code class="code">cbind()</code> always has matrix status. Hence <code class="code">cbind(x)</code> and <code class="code">rbind(x)</code> are possibly the simplest ways explicitly to allow the vector <code class="code">x</code> to be treated as a column or row matrix respectively. </p> <hr> </div> <div class="section-level-extent" id="The-concatenation-function-c_0028_0029-with-arrays"> <div class="nav-panel"> <p> Next: <a href="#Frequency-tables-from-factors" accesskey="n" rel="next">Frequency tables from factors</a>, Previous: <a href="#Forming-partitioned-matrices" accesskey="p" rel="prev">Forming partitioned matrices, <code class="code">cbind()</code> and <code class="code">rbind()</code></a>, Up: <a href="#Arrays-and-matrices" accesskey="u" rel="up">Arrays and matrices</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="The-concatenation-function_002c-c_0028_0029_002c-with-arrays"><span>5.9 The concatenation function, <code class="code">c()</code>, with arrays<a class="copiable-link" href="#The-concatenation-function_002c-c_0028_0029_002c-with-arrays"> ¶</a></span></h3> <p>It should be noted that whereas <code class="code">cbind()</code> and <code class="code">rbind()</code> are concatenation functions that respect <code class="code">dim</code> attributes, the basic <code class="code">c()</code> function does not, but rather clears numeric objects of all <code class="code">dim</code> and <code class="code">dimnames</code> attributes. This is occasionally useful in its own right. </p> <p>The official way to coerce an array back to a simple vector object is to use <code class="code">as.vector()</code> </p> <div class="example"> <pre class="example-preformatted">> vec <- as.vector(X) </pre></div> <a class="index-entry-id" id="index-as_002evector"></a> <p>However a similar result can be achieved by using <code class="code">c()</code> with just one argument, simply for this side-effect: </p> <div class="example"> <pre class="example-preformatted">> vec <- c(X) </pre></div> <a class="index-entry-id" id="index-c-2"></a> <p>There are slight differences between the two, but ultimately the choice between them is largely a matter of style (with the former being preferable). </p> <hr> </div> <div class="section-level-extent" id="Frequency-tables-from-factors"> <div class="nav-panel"> <p> Previous: <a href="#The-concatenation-function-c_0028_0029-with-arrays" accesskey="p" rel="prev">The concatenation function, <code class="code">c()</code>, with arrays</a>, Up: <a href="#Arrays-and-matrices" accesskey="u" rel="up">Arrays and matrices</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Frequency-tables-from-factors-1"><span>5.10 Frequency tables from factors<a class="copiable-link" href="#Frequency-tables-from-factors-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Tabulation"></a> <p>Recall that a factor defines a partition into groups. Similarly a pair of factors defines a two way cross classification, and so on. <a class="index-entry-id" id="index-table-1"></a> The function <code class="code">table()</code> allows frequency tables to be calculated from equal length factors. If there are <em class="math">k</em> factor arguments, the result is a <em class="math">k</em>-way array of frequencies. </p> <p>Suppose, for example, that <code class="code">statef</code> is a factor giving the state code for each entry in a data vector. The assignment </p> <div class="example"> <pre class="example-preformatted">> statefr <- table(statef) </pre></div> <p>gives in <code class="code">statefr</code> a table of frequencies of each state in the sample. The frequencies are ordered and labelled by the <code class="code">levels</code> attribute of the factor. This simple case is equivalent to, but more convenient than, </p> <div class="example"> <pre class="example-preformatted">> statefr <- tapply(statef, statef, length) </pre></div> <p>Further suppose that <code class="code">incomef</code> is a factor giving a suitably defined “income class” for each entry in the data vector, for example with the <code class="code">cut()</code> function: </p> <div class="example"> <pre class="example-preformatted">> factor(cut(incomes, breaks = 35+10*(0:7))) -> incomef </pre></div> <a class="index-entry-id" id="index-cut"></a> <p>Then to calculate a two-way table of frequencies: </p> <div class="example"> <pre class="example-preformatted">> table(incomef,statef) statef incomef act nsw nt qld sa tas vic wa (35,45] 1 1 0 1 0 0 1 0 (45,55] 1 1 1 1 2 0 1 3 (55,65] 0 3 1 3 2 2 2 1 (65,75] 0 1 0 0 0 0 1 0 </pre></div> <p>Extension to higher-way frequency tables is immediate. </p> <hr> </div> </div> <div class="chapter-level-extent" id="Lists-and-data-frames"> <div class="nav-panel"> <p> Next: <a href="#Reading-data-from-files" accesskey="n" rel="next">Reading data from files</a>, Previous: <a href="#Arrays-and-matrices" accesskey="p" rel="prev">Arrays and matrices</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="chapter" id="Lists-and-data-frames-1"><span>6 Lists and data frames<a class="copiable-link" href="#Lists-and-data-frames-1"> ¶</a></span></h2> <ul class="mini-toc"> <li><a href="#Lists" accesskey="1">Lists</a></li> <li><a href="#Constructing-and-modifying-lists" accesskey="2">Constructing and modifying lists</a></li> <li><a href="#Data-frames" accesskey="3">Data frames</a></li> </ul> <hr> <div class="section-level-extent" id="Lists"> <div class="nav-panel"> <p> Next: <a href="#Constructing-and-modifying-lists" accesskey="n" rel="next">Constructing and modifying lists</a>, Previous: <a href="#Lists-and-data-frames" accesskey="p" rel="prev">Lists and data frames</a>, Up: <a href="#Lists-and-data-frames" accesskey="u" rel="up">Lists and data frames</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Lists-1"><span>6.1 Lists<a class="copiable-link" href="#Lists-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Lists"></a> <p>An R <em class="emph">list</em> is an object consisting of an ordered collection of objects known as its <em class="emph">components</em>. </p> <p>There is no particular need for the components to be of the same mode or type, and, for example, a list could consist of a numeric vector, a logical value, a matrix, a complex vector, a character array, a function, and so on. Here is a simple example of how to make a list: </p> <div class="example"> <pre class="example-preformatted">> Lst <- list(name="Fred", wife="Mary", no.children=3, child.ages=c(4,7,9)) </pre></div> <a class="index-entry-id" id="index-list"></a> <p>Components are always <em class="emph">numbered</em> and may always be referred to as such. Thus if <code class="code">Lst</code> is the name of a list with four components, these may be individually referred to as <code class="code">Lst[[1]]</code>, <code class="code">Lst[[2]]</code>, <code class="code">Lst[[3]]</code> and <code class="code">Lst[[4]]</code>. If, further, <code class="code">Lst[[4]]</code> is a vector subscripted array then <code class="code">Lst[[4]][1]</code> is its first entry. </p> <p>If <code class="code">Lst</code> is a list, then the function <code class="code">length(Lst)</code> gives the number of (top level) components it has. </p> <p>Components of lists may also be <em class="emph">named</em>, and in this case the component may be referred to either by giving the component name as a character string in place of the number in double square brackets, or, more conveniently, by giving an expression of the form </p> <div class="example"> <pre class="example-preformatted">> <var class="var">name</var>$<var class="var">component_name</var> </pre></div> <p>for the same thing. </p> <p>This is a very useful convention as it makes it easier to get the right component if you forget the number. </p> <p>So in the simple example given above: </p> <p><code class="code">Lst$name</code> is the same as <code class="code">Lst[[1]]</code> and is the string <code class="code">"Fred"</code>, </p> <p><code class="code">Lst$wife</code> is the same as <code class="code">Lst[[2]]</code> and is the string <code class="code">"Mary"</code>, </p> <p><code class="code">Lst$child.ages[1]</code> is the same as <code class="code">Lst[[4]][1]</code> and is the number <code class="code">4</code>. </p> <p>Additionally, one can also use the names of the list components in double square brackets, i.e., <code class="code">Lst[["name"]]</code> is the same as <code class="code">Lst$name</code>. This is especially useful, when the name of the component to be extracted is stored in another variable as in </p> <div class="example"> <pre class="example-preformatted">> x <- "name"; Lst[[x]] </pre></div> <p>It is very important to distinguish <code class="code">Lst[[1]]</code> from <code class="code">Lst[1]</code>. ‘<samp class="samp"><code class="code">[[<var class="var">…</var>]]</code></samp>’ is the operator used to select a single element, whereas ‘<samp class="samp"><code class="code">[<var class="var">…</var>]</code></samp>’ is a general subscripting operator. Thus the former is the <em class="emph">first object in the list</em> <code class="code">Lst</code>, and if it is a named list the name is <em class="emph">not</em> included. The latter is a <em class="emph">sublist of the list <code class="code">Lst</code> consisting of the first entry only. If it is a named list, the names are transferred to the sublist.</em> </p> <p>The names of components may be abbreviated down to the minimum number of letters needed to identify them uniquely. Thus <code class="code">Lst$coefficients</code> may be minimally specified as <code class="code">Lst$coe</code> and <code class="code">Lst$covariance</code> as <code class="code">Lst$cov</code>. </p> <p>The vector of names is in fact simply an attribute of the list like any other and may be handled as such. Other structures besides lists may, of course, similarly be given a <em class="emph">names</em> attribute also. </p> <hr> </div> <div class="section-level-extent" id="Constructing-and-modifying-lists"> <div class="nav-panel"> <p> Next: <a href="#Data-frames" accesskey="n" rel="next">Data frames</a>, Previous: <a href="#Lists" accesskey="p" rel="prev">Lists</a>, Up: <a href="#Lists-and-data-frames" accesskey="u" rel="up">Lists and data frames</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Constructing-and-modifying-lists-1"><span>6.2 Constructing and modifying lists<a class="copiable-link" href="#Constructing-and-modifying-lists-1"> ¶</a></span></h3> <p>New lists may be formed from existing objects by the function <code class="code">list()</code>. An assignment of the form </p> <div class="example"> <pre class="example-preformatted">> Lst <- list(<var class="var">name_1</var>=<var class="var">object_1</var>, <var class="var">...</var>, <var class="var">name_m</var>=<var class="var">object_m</var>) </pre></div> <p>sets up a list <code class="code">Lst</code> of <em class="math">m</em> components using <var class="var">object_1</var>, …, <var class="var">object_m</var> for the components and giving them names as specified by the argument names, (which can be freely chosen). If these names are omitted, the components are numbered only. The components used to form the list are <em class="emph">copied</em> when forming the new list and the originals are not affected. </p> <p>Lists, like any subscripted object, can be extended by specifying additional components. For example </p> <div class="example"> <pre class="example-preformatted">> Lst[5] <- list(matrix=Mat) </pre></div> <ul class="mini-toc"> <li><a href="#Concatenating-lists" accesskey="1">Concatenating lists</a></li> </ul> <hr> <div class="subsection-level-extent" id="Concatenating-lists"> <div class="nav-panel"> <p> Previous: <a href="#Constructing-and-modifying-lists" accesskey="p" rel="prev">Constructing and modifying lists</a>, Up: <a href="#Constructing-and-modifying-lists" accesskey="u" rel="up">Constructing and modifying lists</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Concatenating-lists-1"><span>6.2.1 Concatenating lists<a class="copiable-link" href="#Concatenating-lists-1"> ¶</a></span></h4> <a class="index-entry-id" id="index-Concatenating-lists"></a> <a class="index-entry-id" id="index-c-3"></a> <p>When the concatenation function <code class="code">c()</code> is given list arguments, the result is an object of mode list also, whose components are those of the argument lists joined together in sequence. </p> <div class="example"> <pre class="example-preformatted">> list.ABC <- c(list.A, list.B, list.C) </pre></div> <p>Recall that with vector objects as arguments the concatenation function similarly joined together all arguments into a single vector structure. In this case all other attributes, such as <code class="code">dim</code> attributes, are discarded. </p> <hr> </div> </div> <div class="section-level-extent" id="Data-frames"> <div class="nav-panel"> <p> Previous: <a href="#Constructing-and-modifying-lists" accesskey="p" rel="prev">Constructing and modifying lists</a>, Up: <a href="#Lists-and-data-frames" accesskey="u" rel="up">Lists and data frames</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Data-frames-1"><span>6.3 Data frames<a class="copiable-link" href="#Data-frames-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Data-frames"></a> <p>A <em class="emph">data frame</em> is a list with class <code class="code">"data.frame"</code>. There are restrictions on lists that may be made into data frames, namely </p> <ul class="itemize mark-bullet"> <li>The components must be vectors (numeric, character, or logical), factors, numeric matrices, lists, or other data frames. </li><li>Matrices, lists, and data frames provide as many variables to the new data frame as they have columns, elements, or variables, respectively. </li><li>Vector structures appearing as variables of the data frame must all have the <em class="emph">same length</em>, and matrix structures must all have the <em class="emph">same number of rows</em>. </li></ul> <p>A data frame may for many purposes be regarded as a matrix with columns possibly of differing modes and attributes. It may be displayed in matrix form, and its rows and columns extracted using matrix indexing conventions. </p> <ul class="mini-toc"> <li><a href="#Making-data-frames" accesskey="1">Making data frames</a></li> <li><a href="#attach_0028_0029-and-detach_0028_0029" accesskey="2"><code class="code">attach()</code> and <code class="code">detach()</code></a></li> <li><a href="#Working-with-data-frames" accesskey="3">Working with data frames</a></li> <li><a href="#Attaching-arbitrary-lists" accesskey="4">Attaching arbitrary lists</a></li> <li><a href="#Managing-the-search-path" accesskey="5">Managing the search path</a></li> </ul> <hr> <div class="subsection-level-extent" id="Making-data-frames"> <div class="nav-panel"> <p> Next: <a href="#attach_0028_0029-and-detach_0028_0029" accesskey="n" rel="next"><code class="code">attach()</code> and <code class="code">detach()</code></a>, Previous: <a href="#Data-frames" accesskey="p" rel="prev">Data frames</a>, Up: <a href="#Data-frames" accesskey="u" rel="up">Data frames</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Making-data-frames-1"><span>6.3.1 Making data frames<a class="copiable-link" href="#Making-data-frames-1"> ¶</a></span></h4> <p>Objects satisfying the restrictions placed on the columns (components) of a data frame may be used to form one using the function <code class="code">data.frame</code>: <a class="index-entry-id" id="index-data_002eframe"></a> </p> <div class="example"> <pre class="example-preformatted">> accountants <- data.frame(home=statef, loot=incomes, shot=incomef) </pre></div> <p>A list whose components conform to the restrictions of a data frame may be <em class="emph">coerced</em> into a data frame using the function <code class="code">as.data.frame()</code> <a class="index-entry-id" id="index-as_002edata_002eframe"></a> </p> <p>The simplest way to construct a data frame from scratch is to use the <code class="code">read.table()</code> function to read an entire data frame from an external file. This is discussed further in <a class="ref" href="#Reading-data-from-files">Reading data from files</a>. </p> <hr> </div> <div class="subsection-level-extent" id="attach_0028_0029-and-detach_0028_0029"> <div class="nav-panel"> <p> Next: <a href="#Working-with-data-frames" accesskey="n" rel="next">Working with data frames</a>, Previous: <a href="#Making-data-frames" accesskey="p" rel="prev">Making data frames</a>, Up: <a href="#Data-frames" accesskey="u" rel="up">Data frames</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="attach_0028_0029-and-detach_0028_0029-1"><span>6.3.2 <code class="code">attach()</code> and <code class="code">detach()</code><a class="copiable-link" href="#attach_0028_0029-and-detach_0028_0029-1"> ¶</a></span></h4> <a class="index-entry-id" id="index-attach"></a> <a class="index-entry-id" id="index-detach"></a> <p>The <code class="code">$</code> notation, such as <code class="code">accountants$home</code>, for list components is not always very convenient. A useful facility would be somehow to make the components of a list or data frame temporarily visible as variables under their component name, without the need to quote the list name explicitly each time. </p> <p>The <code class="code">attach()</code> function takes a ‘database’ such as a list or data frame as its argument. Thus suppose <code class="code">lentils</code> is a data frame with three variables <code class="code">lentils$u</code>, <code class="code">lentils$v</code>, <code class="code">lentils$w</code>. The attach </p> <div class="example"> <pre class="example-preformatted">> attach(lentils) </pre></div> <p>places the data frame in the search path at position 2<!-- /@w -->, and provided there are no variables <code class="code">u</code>, <code class="code">v</code> or <code class="code">w</code> in position 1<!-- /@w -->, <code class="code">u</code>, <code class="code">v</code> and <code class="code">w</code> are available as variables from the data frame in their own right. At this point an assignment such as </p> <div class="example"> <pre class="example-preformatted">> u <- v+w </pre></div> <p>does not replace the component <code class="code">u</code> of the data frame, but rather masks it with another variable <code class="code">u</code> in the workspace at position 1<!-- /@w --> on the search path. To make a permanent change to the data frame itself, the simplest way is to resort once again to the <code class="code">$</code> notation: </p> <div class="example"> <pre class="example-preformatted">> lentils$u <- v+w </pre></div> <p>However the new value of component <code class="code">u</code> is not visible until the data frame is detached and attached again. </p> <p>To detach a data frame, use the function </p> <div class="example"> <pre class="example-preformatted">> detach() </pre></div> <p>More precisely, this statement detaches from the search path the entity currently at position 2<!-- /@w -->. Thus in the present context the variables <code class="code">u</code>, <code class="code">v</code> and <code class="code">w</code> would be no longer visible, except under the list notation as <code class="code">lentils$u</code> and so on. Entities at positions greater than 2 on the search path can be detached by giving their number to <code class="code">detach</code>, but it is much safer to always use a name, for example by <code class="code">detach(lentils)</code> or <code class="code">detach("lentils")</code> </p> <blockquote class="quotation"> <p><b class="b">Note:</b> In R lists and data frames can only be attached at position 2 or above, and what is attached is a <em class="emph">copy</em> of the original object. You can alter the attached values <em class="emph">via</em> <code class="code">assign</code>, but the original list or data frame is unchanged. </p></blockquote> <hr> </div> <div class="subsection-level-extent" id="Working-with-data-frames"> <div class="nav-panel"> <p> Next: <a href="#Attaching-arbitrary-lists" accesskey="n" rel="next">Attaching arbitrary lists</a>, Previous: <a href="#attach_0028_0029-and-detach_0028_0029" accesskey="p" rel="prev"><code class="code">attach()</code> and <code class="code">detach()</code></a>, Up: <a href="#Data-frames" accesskey="u" rel="up">Data frames</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Working-with-data-frames-1"><span>6.3.3 Working with data frames<a class="copiable-link" href="#Working-with-data-frames-1"> ¶</a></span></h4> <p>A useful convention that allows you to work with many different problems comfortably together in the same workspace is </p> <ul class="itemize mark-bullet"> <li>gather together all variables for any well defined and separate problem in a data frame under a suitably informative name; </li><li>when working with a problem attach the appropriate data frame at position 2<!-- /@w -->, and use the workspace at level 1<!-- /@w --> for operational quantities and temporary variables; </li><li>before leaving a problem, add any variables you wish to keep for future reference to the data frame using the <code class="code">$</code> form of assignment, and then <code class="code">detach()</code>; </li><li>finally remove all unwanted variables from the workspace and keep it as clean of left-over temporary variables as possible. </li></ul> <p>In this way it is quite simple to work with many problems in the same directory, all of which have variables named <code class="code">x</code>, <code class="code">y</code> and <code class="code">z</code>, for example. </p> <hr> </div> <div class="subsection-level-extent" id="Attaching-arbitrary-lists"> <div class="nav-panel"> <p> Next: <a href="#Managing-the-search-path" accesskey="n" rel="next">Managing the search path</a>, Previous: <a href="#Working-with-data-frames" accesskey="p" rel="prev">Working with data frames</a>, Up: <a href="#Data-frames" accesskey="u" rel="up">Data frames</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Attaching-arbitrary-lists-1"><span>6.3.4 Attaching arbitrary lists<a class="copiable-link" href="#Attaching-arbitrary-lists-1"> ¶</a></span></h4> <p><code class="code">attach()</code> is a generic function that allows not only directories and data frames to be attached to the search path, but other classes of object as well. In particular any object of mode <code class="code">"list"</code> may be attached in the same way: </p> <div class="example"> <pre class="example-preformatted">> attach(any.old.list) </pre></div> <p>Anything that has been attached can be detached by <code class="code">detach</code>, by position number or, preferably, by name. </p> <hr> </div> <div class="subsection-level-extent" id="Managing-the-search-path"> <div class="nav-panel"> <p> Previous: <a href="#Attaching-arbitrary-lists" accesskey="p" rel="prev">Attaching arbitrary lists</a>, Up: <a href="#Data-frames" accesskey="u" rel="up">Data frames</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Managing-the-search-path-1"><span>6.3.5 Managing the search path<a class="copiable-link" href="#Managing-the-search-path-1"> ¶</a></span></h4> <a class="index-entry-id" id="index-search"></a> <a class="index-entry-id" id="index-Search-path"></a> <p>The function <code class="code">search</code> shows the current search path and so is a very useful way to keep track of which data frames and lists (and packages) have been attached and detached. Initially it gives </p> <div class="example"> <pre class="example-preformatted">> search() [1] ".GlobalEnv" "Autoloads" "package:base" </pre></div> <p>where <code class="code">.GlobalEnv</code> is the workspace.<a class="footnote" id="DOCF18" href="#FOOT18"><sup>18</sup></a> </p> <p>After <code class="code">lentils</code> is attached we have </p> <div class="example"> <pre class="example-preformatted">> search() [1] ".GlobalEnv" "lentils" "Autoloads" "package:base" > ls(2) [1] "u" "v" "w" </pre></div> <p>and as we see <code class="code">ls</code> (or <code class="code">objects</code>) can be used to examine the contents of any position on the search path. </p> <p>Finally, we detach the data frame and confirm it has been removed from the search path. </p> <div class="example"> <pre class="example-preformatted">> detach("lentils") > search() [1] ".GlobalEnv" "Autoloads" "package:base" </pre></div> <hr> </div> </div> </div> <div class="chapter-level-extent" id="Reading-data-from-files"> <div class="nav-panel"> <p> Next: <a href="#Probability-distributions" accesskey="n" rel="next">Probability distributions</a>, Previous: <a href="#Lists-and-data-frames" accesskey="p" rel="prev">Lists and data frames</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="chapter" id="Reading-data-from-files-1"><span>7 Reading data from files<a class="copiable-link" href="#Reading-data-from-files-1"> ¶</a></span></h2> <a class="index-entry-id" id="index-Reading-data-from-files"></a> <p>Large data objects will usually be read as values from external files rather than entered during an R session at the keyboard. R input facilities are simple and their requirements are fairly strict and even rather inflexible. There is a clear presumption by the designers of R that you will be able to modify your input files using other tools, such as file editors or Perl<a class="footnote" id="DOCF19" href="#FOOT19"><sup>19</sup></a> to fit in with the requirements of R. Generally this is very simple. </p> <p>If variables are to be held mainly in data frames, as we strongly suggest they should be, an entire data frame can be read directly with the <code class="code">read.table()</code> function. There is also a more primitive input function, <code class="code">scan()</code>, that can be called directly. </p> <p>For more details on importing data into R and also exporting data, see the <em class="emph">R Data Import/Export</em> manual. </p> <ul class="mini-toc"> <li><a href="#The-read_002etable_0028_0029-function" accesskey="1">The <code class="code">read.table()</code> function</a></li> <li><a href="#The-scan_0028_0029-function" accesskey="2">The <code class="code">scan()</code> function</a></li> <li><a href="#Accessing-builtin-datasets" accesskey="3">Accessing builtin datasets</a></li> <li><a href="#Editing-data" accesskey="4">Editing data</a></li> </ul> <hr> <div class="section-level-extent" id="The-read_002etable_0028_0029-function"> <div class="nav-panel"> <p> Next: <a href="#The-scan_0028_0029-function" accesskey="n" rel="next">The <code class="code">scan()</code> function</a>, Previous: <a href="#Reading-data-from-files" accesskey="p" rel="prev">Reading data from files</a>, Up: <a href="#Reading-data-from-files" accesskey="u" rel="up">Reading data from files</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="The-read_002etable_0028_0029-function-1"><span>7.1 The <code class="code">read.table()</code> function<a class="copiable-link" href="#The-read_002etable_0028_0029-function-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-read_002etable"></a> <p>To read an entire data frame directly, the external file will normally have a special form. </p> <ul class="itemize mark-bullet"> <li>The first line of the file should have a <em class="emph">name</em> for each variable in the data frame. </li><li>Each additional line of the file has as its first item a <em class="emph">row label</em> and the values for each variable. </li></ul> <p>If the file has one fewer item in its first line than in its second, this arrangement is presumed to be in force. So the first few lines of a file to be read as a data frame might look as follows. </p> <blockquote class="quotation"> <table summary="" class="cartouche" border="1"><tr><td> <div class="example"> <pre class="example-preformatted"><span class="r">Input file form with names and row labels:</span> Price Floor Area Rooms Age Cent.heat 01 52.00 111.0 830 5 6.2 no 02 54.75 128.0 710 5 7.5 no 03 57.50 101.0 1000 5 4.2 no 04 57.50 131.0 690 6 8.8 no 05 59.75 93.0 900 5 1.9 yes ... </pre></div> </td></tr></table> </blockquote> <p>By default numeric items (except row labels) are read as numeric variables and non-numeric variables, such as <code class="code">Cent.heat</code> in the example, as character variables. This can be changed if necessary. </p> <p>The function <code class="code">read.table()</code> can then be used to read the data frame directly </p> <div class="example"> <pre class="example-preformatted">> HousePrice <- read.table("houses.data") </pre></div> <p>Often you will want to omit including the row labels directly and use the default labels. In this case the file may omit the row label column as in the following. </p> <blockquote class="quotation"> <table summary="" class="cartouche" border="1"><tr><td> <div class="example"> <pre class="example-preformatted"><span class="r">Input file form without row labels:</span> Price Floor Area Rooms Age Cent.heat 52.00 111.0 830 5 6.2 no 54.75 128.0 710 5 7.5 no 57.50 101.0 1000 5 4.2 no 57.50 131.0 690 6 8.8 no 59.75 93.0 900 5 1.9 yes ... </pre></div> </td></tr></table> </blockquote> <p>The data frame may then be read as </p> <div class="example"> <pre class="example-preformatted">> HousePrice <- read.table("houses.data", header=TRUE) </pre></div> <p>where the <code class="code">header=TRUE</code> option specifies that the first line is a line of headings, and hence, by implication from the form of the file, that no explicit row labels are given. </p> <hr> </div> <div class="section-level-extent" id="The-scan_0028_0029-function"> <div class="nav-panel"> <p> Next: <a href="#Accessing-builtin-datasets" accesskey="n" rel="next">Accessing builtin datasets</a>, Previous: <a href="#The-read_002etable_0028_0029-function" accesskey="p" rel="prev">The <code class="code">read.table()</code> function</a>, Up: <a href="#Reading-data-from-files" accesskey="u" rel="up">Reading data from files</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="The-scan_0028_0029-function-1"><span>7.2 The <code class="code">scan()</code> function<a class="copiable-link" href="#The-scan_0028_0029-function-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-scan"></a> <p>Suppose the data vectors are of equal length and are to be read in parallel. Further suppose that there are three vectors, the first of mode character and the remaining two of mode numeric, and the file is <samp class="file">input.dat</samp>. The first step is to use <code class="code">scan()</code> to read in the three vectors as a list, as follows </p> <div class="example"> <pre class="example-preformatted">> inp <- scan("input.dat", list("",0,0)) </pre></div> <p>The second argument is a dummy list structure that establishes the mode of the three vectors to be read. The result, held in <code class="code">inp</code>, is a list whose components are the three vectors read in. To separate the data items into three separate vectors, use assignments like </p> <div class="example"> <pre class="example-preformatted">> label <- inp[[1]]; x <- inp[[2]]; y <- inp[[3]] </pre></div> <p>More conveniently, the dummy list can have named components, in which case the names can be used to access the vectors read in. For example </p> <div class="example"> <pre class="example-preformatted">> inp <- scan("input.dat", list(id="", x=0, y=0)) </pre></div> <p>If you wish to access the variables separately they may either be re-assigned to variables in the working frame: </p> <div class="example"> <pre class="example-preformatted">> label <- inp$id; x <- inp$x; y <- inp$y </pre></div> <p>or the list may be attached at position 2<!-- /@w --> of the search path (see <a class="pxref" href="#Attaching-arbitrary-lists">Attaching arbitrary lists</a>). </p> <p>If the second argument is a single value and not a list, a single vector is read in, all components of which must be of the same mode as the dummy value. </p> <div class="example"> <pre class="example-preformatted">> X <- matrix(scan("light.dat", 0), ncol=5, byrow=TRUE) </pre></div> <p>There are more elaborate input facilities available and these are detailed in the manuals. </p> <hr> </div> <div class="section-level-extent" id="Accessing-builtin-datasets"> <div class="nav-panel"> <p> Next: <a href="#Editing-data" accesskey="n" rel="next">Editing data</a>, Previous: <a href="#The-scan_0028_0029-function" accesskey="p" rel="prev">The <code class="code">scan()</code> function</a>, Up: <a href="#Reading-data-from-files" accesskey="u" rel="up">Reading data from files</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Accessing-builtin-datasets-1"><span>7.3 Accessing builtin datasets<a class="copiable-link" href="#Accessing-builtin-datasets-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Accessing-builtin-datasets"></a> <a class="index-entry-id" id="index-data"></a> <p>Around 100 datasets are supplied with R (in package <strong class="strong">datasets</strong>), and others are available in packages (including the recommended packages supplied with R). To see the list of datasets currently available use </p> <div class="example"> <pre class="example-preformatted">data() </pre></div> <p>All the datasets supplied with R are available directly by name. However, many packages still use the obsolete convention in which <code class="code">data</code> was also used to load datasets into R, for example </p> <div class="example"> <pre class="example-preformatted">data(infert) </pre></div> <p>and this can still be used with the standard packages (as in this example). In most cases this will load an R object of the same name. However, in a few cases it loads several objects, so see the on-line help for the object to see what to expect. </p> <ul class="mini-toc"> <li><a href="#Loading-data-from-other-R-packages" accesskey="1">Loading data from other R packages</a></li> </ul> <div class="subsection-level-extent" id="Loading-data-from-other-R-packages"> <h4 class="subsection"><span>7.3.1 Loading data from other R packages<a class="copiable-link" href="#Loading-data-from-other-R-packages"> ¶</a></span></h4> <p>To access data from a particular package, use the <code class="code">package</code> argument, for example </p> <div class="example"> <pre class="example-preformatted">data(package="rpart") data(Puromycin, package="datasets") </pre></div> <p>If a package has been attached by <code class="code">library</code>, its datasets are automatically included in the search. </p> <p>User-contributed packages can be a rich source of datasets. </p> <hr> </div> </div> <div class="section-level-extent" id="Editing-data"> <div class="nav-panel"> <p> Previous: <a href="#Accessing-builtin-datasets" accesskey="p" rel="prev">Accessing builtin datasets</a>, Up: <a href="#Reading-data-from-files" accesskey="u" rel="up">Reading data from files</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Editing-data-1"><span>7.4 Editing data<a class="copiable-link" href="#Editing-data-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-edit"></a> <p>When invoked on a data frame or matrix, <code class="code">edit</code> brings up a separate spreadsheet-like environment for editing. This is useful for making small changes once a data set has been read. The command </p> <div class="example"> <pre class="example-preformatted">> xnew <- edit(xold) </pre></div> <p>will allow you to edit your data set <code class="code">xold</code>, and on completion the changed object is assigned to <code class="code">xnew</code>. If you want to alter the original dataset <code class="code">xold</code>, the simplest way is to use <code class="code">fix(xold)</code>, which is equivalent to <code class="code">xold <- edit(xold)</code>. </p> <p>Use </p> <div class="example"> <pre class="example-preformatted">> xnew <- edit(data.frame()) </pre></div> <p>to enter new data via the spreadsheet interface. </p> <hr> </div> </div> <div class="chapter-level-extent" id="Probability-distributions"> <div class="nav-panel"> <p> Next: <a href="#Loops-and-conditional-execution" accesskey="n" rel="next">Grouping, loops and conditional execution</a>, Previous: <a href="#Reading-data-from-files" accesskey="p" rel="prev">Reading data from files</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="chapter" id="Probability-distributions-1"><span>8 Probability distributions<a class="copiable-link" href="#Probability-distributions-1"> ¶</a></span></h2> <a class="index-entry-id" id="index-Probability-distributions"></a> <ul class="mini-toc"> <li><a href="#R-as-a-set-of-statistical-tables" accesskey="1">R as a set of statistical tables</a></li> <li><a href="#Examining-the-distribution-of-a-set-of-data" accesskey="2">Examining the distribution of a set of data</a></li> <li><a href="#One_002d-and-two_002dsample-tests" accesskey="3">One- and two-sample tests</a></li> </ul> <hr> <div class="section-level-extent" id="R-as-a-set-of-statistical-tables"> <div class="nav-panel"> <p> Next: <a href="#Examining-the-distribution-of-a-set-of-data" accesskey="n" rel="next">Examining the distribution of a set of data</a>, Previous: <a href="#Probability-distributions" accesskey="p" rel="prev">Probability distributions</a>, Up: <a href="#Probability-distributions" accesskey="u" rel="up">Probability distributions</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="R-as-a-set-of-statistical-tables-1"><span>8.1 R as a set of statistical tables<a class="copiable-link" href="#R-as-a-set-of-statistical-tables-1"> ¶</a></span></h3> <p>One convenient use of R is to provide a comprehensive set of statistical tables. Functions are provided to evaluate the cumulative distribution function P(X <= x), the probability density function and the quantile function (given <em class="math">q</em>, the smallest <em class="math">x</em> such that P(X <= x) > q), and to simulate from the distribution. </p> <blockquote class="quotation"> <table summary="" class="multitable"> <thead><tr><th>Distribution</th><th>R name</th><th>additional arguments</th></tr></thead> <tbody><tr><td>beta</td><td><code class="code">beta</code></td><td><code class="code">shape1, shape2, ncp</code></td></tr> <tr><td>binomial</td><td><code class="code">binom</code></td><td><code class="code">size, prob</code></td></tr> <tr><td>Cauchy</td><td><code class="code">cauchy</code></td><td><code class="code">location, scale</code></td></tr> <tr><td>chi-squared</td><td><code class="code">chisq</code></td><td><code class="code">df, ncp</code></td></tr> <tr><td>exponential</td><td><code class="code">exp</code></td><td><code class="code">rate</code></td></tr> <tr><td>F</td><td><code class="code">f</code></td><td><code class="code">df1, df2, ncp</code></td></tr> <tr><td>gamma</td><td><code class="code">gamma</code></td><td><code class="code">shape, scale</code></td></tr> <tr><td>geometric</td><td><code class="code">geom</code></td><td><code class="code">prob</code></td></tr> <tr><td>hypergeometric</td><td><code class="code">hyper</code></td><td><code class="code">m, n, k</code></td></tr> <tr><td>log-normal</td><td><code class="code">lnorm</code></td><td><code class="code">meanlog, sdlog</code></td></tr> <tr><td>logistic</td><td><code class="code">logis</code></td><td><code class="code">location, scale</code></td></tr> <tr><td>negative binomial</td><td><code class="code">nbinom</code></td><td><code class="code">size, prob</code></td></tr> <tr><td>normal</td><td><code class="code">norm</code></td><td><code class="code">mean, sd</code></td></tr> <tr><td>Poisson</td><td><code class="code">pois</code></td><td><code class="code">lambda</code></td></tr> <tr><td>signed rank</td><td><code class="code">signrank</code></td><td><code class="code">n</code></td></tr> <tr><td>Student’s t</td><td><code class="code">t</code></td><td><code class="code">df, ncp</code></td></tr> <tr><td>uniform</td><td><code class="code">unif</code></td><td><code class="code">min, max</code></td></tr> <tr><td>Weibull</td><td><code class="code">weibull</code></td><td><code class="code">shape, scale</code></td></tr> <tr><td>Wilcoxon</td><td><code class="code">wilcox</code></td><td><code class="code">m, n</code></td></tr> </tbody> </table> </blockquote> <p>Prefix the name given here by ‘<samp class="samp">d</samp>’ for the density, ‘<samp class="samp">p</samp>’ for the CDF, ‘<samp class="samp">q</samp>’ for the quantile function and ‘<samp class="samp">r</samp>’ for simulation (<em class="emph">r</em>andom deviates). The first argument is <code class="code">x</code> for <code class="code">d<var class="var">xxx</var></code>, <code class="code">q</code> for <code class="code">p<var class="var">xxx</var></code>, <code class="code">p</code> for <code class="code">q<var class="var">xxx</var></code> and <code class="code">n</code> for <code class="code">r<var class="var">xxx</var></code> (except for <code class="code">rhyper</code>, <code class="code">rsignrank</code> and <code class="code">rwilcox</code>, for which it is <code class="code">nn</code>). In not quite all cases is the non-centrality parameter <code class="code">ncp</code> currently available: see the on-line help for details. </p> <p>The <code class="code">p<var class="var">xxx</var></code> and <code class="code">q<var class="var">xxx</var></code> functions all have logical arguments <code class="code">lower.tail</code> and <code class="code">log.p</code> and the <code class="code">d<var class="var">xxx</var></code> ones have <code class="code">log</code>. This allows, e.g., getting the cumulative (or “integrated”) <em class="emph">hazard</em> function, H(t) = - log(1 - F(t)), by </p> <div class="example"> <pre class="example-preformatted"> - p<var class="var">xxx</var>(t, ..., lower.tail = FALSE, log.p = TRUE) </pre></div> <p>or more accurate log-likelihoods (by <code class="code">d<var class="var">xxx</var>(..., log = TRUE)</code>), directly. </p> <p>In addition there are functions <code class="code">ptukey</code> and <code class="code">qtukey</code> for the distribution of the studentized range of samples from a normal distribution, and <code class="code">dmultinom</code> and <code class="code">rmultinom</code> for the multinomial distribution. Further distributions are available in contributed packages, notably <a class="url" href="https://CRAN.R-project.org/package=SuppDists"><strong class="strong">SuppDists</strong></a>. </p> <p>Here are some examples </p> <div class="example"> <pre class="example-preformatted">> ## <span class="r">2-tailed p-value for t distribution</span> > 2*pt(-2.43, df = 13) > ## <span class="r">upper 1% point for an F(2, 7) distribution</span> > qf(0.01, 2, 7, lower.tail = FALSE) </pre></div> <p>See the on-line help on <code class="code">RNG</code> for how random-number generation is done in R. </p> <hr> </div> <div class="section-level-extent" id="Examining-the-distribution-of-a-set-of-data"> <div class="nav-panel"> <p> Next: <a href="#One_002d-and-two_002dsample-tests" accesskey="n" rel="next">One- and two-sample tests</a>, Previous: <a href="#R-as-a-set-of-statistical-tables" accesskey="p" rel="prev">R as a set of statistical tables</a>, Up: <a href="#Probability-distributions" accesskey="u" rel="up">Probability distributions</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Examining-the-distribution-of-a-set-of-data-1"><span>8.2 Examining the distribution of a set of data<a class="copiable-link" href="#Examining-the-distribution-of-a-set-of-data-1"> ¶</a></span></h3> <p>Given a (univariate) set of data we can examine its distribution in a large number of ways. The simplest is to examine the numbers. Two slightly different summaries are given by <code class="code">summary</code> and <code class="code">fivenum</code> <a class="index-entry-id" id="index-summary"></a> <a class="index-entry-id" id="index-fivenum"></a> and a display of the numbers by <code class="code">stem</code> (a “stem and leaf” plot). <a class="index-entry-id" id="index-stem"></a> </p> <div class="example"> <pre class="example-preformatted">> attach(faithful) > summary(eruptions) Min. 1st Qu. Median Mean 3rd Qu. Max. 1.600 2.163 4.000 3.488 4.454 5.100 > fivenum(eruptions) [1] 1.6000 2.1585 4.0000 4.4585 5.1000 > stem(eruptions) The decimal point is 1 digit(s) to the left of the | 16 | 070355555588 18 | 000022233333335577777777888822335777888 20 | 00002223378800035778 22 | 0002335578023578 24 | 00228 26 | 23 28 | 080 30 | 7 32 | 2337 34 | 250077 36 | 0000823577 38 | 2333335582225577 40 | 0000003357788888002233555577778 42 | 03335555778800233333555577778 44 | 02222335557780000000023333357778888 46 | 0000233357700000023578 48 | 00000022335800333 50 | 0370 </pre></div> <p>A stem-and-leaf plot is like a histogram, and R has a function <code class="code">hist</code> to plot histograms. <a class="index-entry-id" id="index-hist"></a> </p> <div class="example"> <pre class="example-preformatted">> hist(eruptions) ## <span class="r">make the bins smaller, make a plot of density</span> > hist(eruptions, seq(1.6, 5.2, 0.2), prob=TRUE) > lines(density(eruptions, bw=0.1)) > rug(eruptions) # <span class="r">show the actual data points</span> </pre></div> <a class="index-entry-id" id="index-density"></a> <a class="index-entry-id" id="index-Density-estimation"></a> <p>More elegant density plots can be made by <code class="code">density</code>, and we added a line produced by <code class="code">density</code> in this example. The bandwidth <code class="code">bw</code> was chosen by trial-and-error as the default gives too much smoothing (it usually does for “interesting” densities). (Better automated methods of bandwidth choice are available, and in this example <code class="code">bw = "SJ"</code> gives a good result.) </p> <img class="image" src="images/hist.png" alt="images/hist"> <p>We can plot the empirical cumulative distribution function by using the function <code class="code">ecdf</code>. <a class="index-entry-id" id="index-ecdf"></a> <a class="index-entry-id" id="index-Empirical-CDFs"></a> </p> <div class="example"> <pre class="example-preformatted">> plot(ecdf(eruptions), do.points=FALSE, verticals=TRUE) </pre></div> <p>This distribution is obviously far from any standard distribution. How about the right-hand mode, say eruptions of longer than 3 minutes? Let us fit a normal distribution and overlay the fitted CDF. </p> <div class="example"> <pre class="example-preformatted">> long <- eruptions[eruptions > 3] > plot(ecdf(long), do.points=FALSE, verticals=TRUE) > x <- seq(3, 5.4, 0.01) > lines(x, pnorm(x, mean=mean(long), sd=sqrt(var(long))), lty=3) </pre></div> <img class="image" src="images/ecdf.png" alt="images/ecdf"> <p>Quantile-quantile (Q-Q) plots can help us examine this more carefully. <a class="index-entry-id" id="index-Quantile_002dquantile-plots"></a> <a class="index-entry-id" id="index-qqnorm"></a> <a class="index-entry-id" id="index-qqline"></a> </p> <div class="example"> <pre class="example-preformatted">par(pty="s") # arrange for a square figure region qqnorm(long); qqline(long) </pre></div> <p>which shows a reasonable fit but a shorter right tail than one would expect from a normal distribution. Let us compare this with some simulated data from a <em class="math">t</em> distribution </p> <img class="image" src="images/QQ.png" alt="images/QQ"> <div class="example"> <pre class="example-preformatted">x <- rt(250, df = 5) qqnorm(x); qqline(x) </pre></div> <p>which will usually (if it is a random sample) show longer tails than expected for a normal. We can make a Q-Q plot against the generating distribution by </p> <div class="example"> <pre class="example-preformatted">qqplot(qt(ppoints(250), df = 5), x, xlab = "Q-Q plot for t dsn") qqline(x) </pre></div> <p>Finally, we might want a more formal test of agreement with normality (or not). R provides the Shapiro-Wilk test <a class="index-entry-id" id="index-Shapiro_002dWilk-test"></a> <a class="index-entry-id" id="index-shapiro_002etest"></a> </p> <div class="example"> <pre class="example-preformatted">> shapiro.test(long) Shapiro-Wilk normality test data: long W = 0.9793, p-value = 0.01052 </pre></div> <p>and the Kolmogorov-Smirnov test <a class="index-entry-id" id="index-Kolmogorov_002dSmirnov-test"></a> <a class="index-entry-id" id="index-ks_002etest"></a> </p> <div class="example"> <pre class="example-preformatted">> ks.test(long, "pnorm", mean = mean(long), sd = sqrt(var(long))) One-sample Kolmogorov-Smirnov test data: long D = 0.0661, p-value = 0.4284 alternative hypothesis: two.sided </pre></div> <p>(Note that the distribution theory is not valid here as we have estimated the parameters of the normal distribution from the same sample.) </p> <hr> </div> <div class="section-level-extent" id="One_002d-and-two_002dsample-tests"> <div class="nav-panel"> <p> Previous: <a href="#Examining-the-distribution-of-a-set-of-data" accesskey="p" rel="prev">Examining the distribution of a set of data</a>, Up: <a href="#Probability-distributions" accesskey="u" rel="up">Probability distributions</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="One_002d-and-two_002dsample-tests-1"><span>8.3 One- and two-sample tests<a class="copiable-link" href="#One_002d-and-two_002dsample-tests-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-One_002d-and-two_002dsample-tests"></a> <p>So far we have compared a single sample to a normal distribution. A much more common operation is to compare aspects of two samples. Note that in R, all “classical” tests including the ones used below are in package <strong class="strong">stats</strong> which is normally loaded. </p> <p>Consider the following sets of data on the latent heat of the fusion of ice (<em class="emph">cal/gm</em>) from Rice (1995, p.490) </p> <div class="example"> <pre class="example-preformatted">Method A: 79.98 80.04 80.02 80.04 80.03 80.03 80.04 79.97 80.05 80.03 80.02 80.00 80.02 Method B: 80.02 79.94 79.98 79.97 79.97 80.03 79.95 79.97 </pre></div> <p>Boxplots provide a simple graphical comparison of the two samples. </p> <div class="example"> <pre class="example-preformatted">A <- scan() 79.98 80.04 80.02 80.04 80.03 80.03 80.04 79.97 80.05 80.03 80.02 80.00 80.02 B <- scan() 80.02 79.94 79.98 79.97 79.97 80.03 79.95 79.97 boxplot(A, B) </pre></div> <a class="index-entry-id" id="index-boxplot"></a> <a class="index-entry-id" id="index-Box-plots"></a> <p>which indicates that the first group tends to give higher results than the second. </p> <img class="image" src="images/ice.png" alt="images/ice"> <p>To test for the equality of the means of the two examples, we can use an <em class="emph">unpaired</em> <em class="math">t</em>-test by <a class="index-entry-id" id="index-Student_0027s-t-test"></a> <a class="index-entry-id" id="index-t_002etest"></a> </p> <div class="example"> <pre class="example-preformatted">> t.test(A, B) Welch Two Sample t-test data: A and B t = 3.2499, df = 12.027, p-value = 0.00694 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: 0.01385526 0.07018320 sample estimates: mean of x mean of y 80.02077 79.97875 </pre></div> <p>which does indicate a significant difference, assuming normality. By default the R function does not assume equality of variances in the two samples. We can use the F test to test for equality in the variances, provided that the two samples are from normal populations. </p> <div class="example"> <pre class="example-preformatted">> var.test(A, B) F test to compare two variances data: A and B F = 0.5837, num df = 12, denom df = 7, p-value = 0.3938 alternative hypothesis: true ratio of variances is not equal to 1 95 percent confidence interval: 0.1251097 2.1052687 sample estimates: ratio of variances 0.5837405 </pre></div> <a class="index-entry-id" id="index-var_002etest"></a> <p>which shows no evidence of a significant difference, and so we can use the classical <em class="math">t</em>-test that assumes equality of the variances. </p> <div class="example"> <pre class="example-preformatted">> t.test(A, B, var.equal=TRUE) Two Sample t-test data: A and B t = 3.4722, df = 19, p-value = 0.002551 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: 0.01669058 0.06734788 sample estimates: mean of x mean of y 80.02077 79.97875 </pre></div> <p>All these tests assume normality of the two samples. The two-sample Wilcoxon (or Mann-Whitney) test only assumes a common continuous distribution under the null hypothesis. </p> <a class="index-entry-id" id="index-Wilcoxon-test"></a> <a class="index-entry-id" id="index-wilcox_002etest"></a> <div class="example"> <pre class="example-preformatted">> wilcox.test(A, B) Wilcoxon rank sum test with continuity correction data: A and B W = 89, p-value = 0.007497 alternative hypothesis: true location shift is not equal to 0 Warning message: Cannot compute exact p-value with ties in: wilcox.test(A, B) </pre></div> <p>Note the warning: there are several ties in each sample, which suggests strongly that these data are from a discrete distribution (probably due to rounding). </p> <p>There are several ways to compare graphically the two samples. We have already seen a pair of boxplots. The following </p> <div class="example"> <pre class="example-preformatted">> plot(ecdf(A), do.points=FALSE, verticals=TRUE, xlim=range(A, B)) > plot(ecdf(B), do.points=FALSE, verticals=TRUE, add=TRUE) </pre></div> <p>will show the two empirical CDFs, and <code class="code">qqplot</code> will perform a Q-Q plot of the two samples. The Kolmogorov-Smirnov test is of the maximal vertical distance between the two <abbr class="abbr">ecdf</abbr>s, assuming a common continuous distribution: </p> <div class="example"> <pre class="example-preformatted">> ks.test(A, B) Two-sample Kolmogorov-Smirnov test data: A and B D = 0.5962, p-value = 0.05919 alternative hypothesis: two-sided Warning message: cannot compute correct p-values with ties in: ks.test(A, B) </pre></div> <hr> </div> </div> <div class="chapter-level-extent" id="Loops-and-conditional-execution"> <div class="nav-panel"> <p> Next: <a href="#Writing-your-own-functions" accesskey="n" rel="next">Writing your own functions</a>, Previous: <a href="#Probability-distributions" accesskey="p" rel="prev">Probability distributions</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="chapter" id="Grouping_002c-loops-and-conditional-execution"><span>9 Grouping, loops and conditional execution<a class="copiable-link" href="#Grouping_002c-loops-and-conditional-execution"> ¶</a></span></h2> <a class="index-entry-id" id="index-Loops-and-conditional-execution"></a> <ul class="mini-toc"> <li><a href="#Grouped-expressions" accesskey="1">Grouped expressions</a></li> <li><a href="#Control-statements" accesskey="2">Control statements</a></li> </ul> <hr> <div class="section-level-extent" id="Grouped-expressions"> <div class="nav-panel"> <p> Next: <a href="#Control-statements" accesskey="n" rel="next">Control statements</a>, Previous: <a href="#Loops-and-conditional-execution" accesskey="p" rel="prev">Grouping, loops and conditional execution</a>, Up: <a href="#Loops-and-conditional-execution" accesskey="u" rel="up">Grouping, loops and conditional execution</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Grouped-expressions-1"><span>9.1 Grouped expressions<a class="copiable-link" href="#Grouped-expressions-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Grouped-expressions"></a> <p>R is an expression language in the sense that its only command type is a function or expression which returns a result. Even an assignment is an expression whose result is the value assigned, and it may be used wherever any expression may be used; in particular multiple assignments are possible. </p> <p>Commands may be grouped together in braces, <code class="code">{<var class="var">expr_1</var>; <var class="var">…</var>; <var class="var">expr_m</var>}</code>, in which case the value of the group is the result of the last expression in the group evaluated. Since such a group is also an expression it may, for example, be itself included in parentheses and used as part of an even larger expression, and so on. </p> <hr> </div> <div class="section-level-extent" id="Control-statements"> <div class="nav-panel"> <p> Previous: <a href="#Grouped-expressions" accesskey="p" rel="prev">Grouped expressions</a>, Up: <a href="#Loops-and-conditional-execution" accesskey="u" rel="up">Grouping, loops and conditional execution</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Control-statements-1"><span>9.2 Control statements<a class="copiable-link" href="#Control-statements-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Control-statements"></a> <ul class="mini-toc"> <li><a href="#Conditional-execution" accesskey="1">Conditional execution: <code class="code">if</code> statements</a></li> <li><a href="#Repetitive-execution" accesskey="2">Repetitive execution: <code class="code">for</code> loops, <code class="code">repeat</code> and <code class="code">while</code></a></li> </ul> <hr> <div class="subsection-level-extent" id="Conditional-execution"> <div class="nav-panel"> <p> Next: <a href="#Repetitive-execution" accesskey="n" rel="next">Repetitive execution: <code class="code">for</code> loops, <code class="code">repeat</code> and <code class="code">while</code></a>, Previous: <a href="#Control-statements" accesskey="p" rel="prev">Control statements</a>, Up: <a href="#Control-statements" accesskey="u" rel="up">Control statements</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Conditional-execution_003a-if-statements"><span>9.2.1 Conditional execution: <code class="code">if</code> statements<a class="copiable-link" href="#Conditional-execution_003a-if-statements"> ¶</a></span></h4> <a class="index-entry-id" id="index-if"></a> <p>The language has available a conditional construction of the form </p> <div class="example"> <pre class="example-preformatted">> if (<var class="var">expr_1</var>) <var class="var">expr_2</var> else <var class="var">expr_3</var> </pre></div> <a class="index-entry-id" id="index-if-1"></a> <a class="index-entry-id" id="index-else"></a> <p>where <var class="var">expr_1</var> must evaluate to a single logical value and the result of the entire expression is then evident. </p> <a class="index-entry-id" id="index-_0026_0026"></a> <a class="index-entry-id" id="index-_007c_007c"></a> <p>The “short-circuit” operators <code class="code">&&</code> and <code class="code">||</code> are often used as part of the condition in an <code class="code">if</code> statement. Whereas <code class="code">&</code> and <code class="code">|</code> apply element-wise to vectors, <code class="code">&&</code> and <code class="code">||</code> apply to vectors of length one, and only evaluate their second argument if necessary. </p> <a class="index-entry-id" id="index-ifelse"></a> <p>There is a vectorized version of the <code class="code">if</code>/<code class="code">else</code> construct, the <code class="code">ifelse</code> function. This has the form <code class="code">ifelse(condition, a, b)</code> and returns a vector of the same length as <code class="code">condition</code>, with elements <code class="code">a[i]</code> if <code class="code">condition[i]</code> is true, otherwise <code class="code">b[i]</code> (where <code class="code">a</code> and <code class="code">b</code> are recycled as necessary). </p> <hr> </div> <div class="subsection-level-extent" id="Repetitive-execution"> <div class="nav-panel"> <p> Previous: <a href="#Conditional-execution" accesskey="p" rel="prev">Conditional execution: <code class="code">if</code> statements</a>, Up: <a href="#Control-statements" accesskey="u" rel="up">Control statements</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Repetitive-execution_003a-for-loops_002c-repeat-and-while"><span>9.2.2 Repetitive execution: <code class="code">for</code> loops, <code class="code">repeat</code> and <code class="code">while</code><a class="copiable-link" href="#Repetitive-execution_003a-for-loops_002c-repeat-and-while"> ¶</a></span></h4> <a class="index-entry-id" id="index-for"></a> <p>There is also a <code class="code">for</code> loop construction which has the form </p> <div class="example"> <pre class="example-preformatted">> for (<code class="code"><var class="var">name</var></code> in <var class="var">expr_1</var>) <var class="var">expr_2</var> </pre></div> <p>where <code class="code"><var class="var">name</var></code> is the loop variable. <var class="var">expr_1</var> is a vector expression, (often a sequence like <code class="code">1:20</code>), and <var class="var">expr_2</var> is often a grouped expression with its sub-expressions written in terms of the dummy <em class="emph">name</em>. <var class="var">expr_2</var> is repeatedly evaluated as <var class="var">name</var> ranges through the values in the vector result of <var class="var">expr_1</var>. </p> <p>As an example, suppose <code class="code">ind</code> is a vector of class indicators and we wish to produce separate plots of <code class="code">y</code> versus <code class="code">x</code> within classes. One possibility here is to use <code class="code">coplot()</code>,<a class="footnote" id="DOCF20" href="#FOOT20"><sup>20</sup></a> which will produce an array of plots corresponding to each level of the factor. Another way to do this, now putting all plots on the one display, is as follows: </p> <div class="example"> <pre class="example-preformatted">> xc <- split(x, ind) > yc <- split(y, ind) > for (i in 1:length(yc)) { plot(xc[[i]], yc[[i]]) abline(lsfit(xc[[i]], yc[[i]])) } </pre></div> <a class="index-entry-id" id="index-split"></a> <p>(Note the function <code class="code">split()</code> which produces a list of vectors obtained by splitting a larger vector according to the classes specified by a factor. This is a useful function, mostly used in connection with boxplots. See the <code class="code">help</code> facility for further details.) </p> <blockquote class="quotation"> <p><strong class="strong">Warning</strong>: <code class="code">for()</code> loops are used in R code much less often than in compiled languages. Code that takes a ‘whole object’ view is likely to be both clearer and faster in R. </p></blockquote> <p>Other looping facilities include the </p> <div class="example"> <pre class="example-preformatted">> repeat <var class="var">expr</var> </pre></div> <a class="index-entry-id" id="index-repeat"></a> <p>statement and the </p> <div class="example"> <pre class="example-preformatted">> while (<var class="var">condition</var>) <var class="var">expr</var> </pre></div> <a class="index-entry-id" id="index-while"></a> <p>statement. </p> <p>The <code class="code">break</code> statement can be used to terminate any loop, possibly abnormally. This is the only way to terminate <code class="code">repeat</code> loops. <a class="index-entry-id" id="index-break"></a> </p> <p>The <code class="code">next</code> statement can be used to discontinue one particular cycle and skip to the “next”. <a class="index-entry-id" id="index-next"></a> </p> <p>Control statements are most often used in connection with <em class="emph">functions</em> which are discussed in <a class="ref" href="#Writing-your-own-functions">Writing your own functions</a>, and where more examples will emerge. </p> <hr> </div> </div> </div> <div class="chapter-level-extent" id="Writing-your-own-functions"> <div class="nav-panel"> <p> Next: <a href="#Statistical-models-in-R" accesskey="n" rel="next">Statistical models in R</a>, Previous: <a href="#Loops-and-conditional-execution" accesskey="p" rel="prev">Grouping, loops and conditional execution</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="chapter" id="Writing-your-own-functions-1"><span>10 Writing your own functions<a class="copiable-link" href="#Writing-your-own-functions-1"> ¶</a></span></h2> <a class="index-entry-id" id="index-Writing-functions"></a> <p>As we have seen informally along the way, the R language allows the user to create objects of mode <em class="emph">function</em>. These are true R functions that are stored in a special internal form and may be used in further expressions and so on. In the process, the language gains enormously in power, convenience and elegance, and learning to write useful functions is one of the main ways to make your use of R comfortable and productive. </p> <p>It should be emphasized that most of the functions supplied as part of the R system, such as <code class="code">mean()</code>, <code class="code">var()</code>, <code class="code">postscript()</code> and so on, are themselves written in R and thus do not differ materially from user written functions. </p> <p>A function is defined by an assignment of the form </p> <div class="example"> <pre class="example-preformatted">> <var class="var">name</var> <- function(<var class="var">arg_1</var>, <var class="var">arg_2</var>, ...) <var class="var">expression</var> </pre></div> <a class="index-entry-id" id="index-function"></a> <p>The <var class="var">expression</var> is an R expression, (usually a grouped expression), that uses the arguments, <var class="var">arg_i</var>, to calculate a value. The value of the expression is the value returned for the function. </p> <p>A call to the function then usually takes the form <code class="code"><var class="var">name</var>(<var class="var">expr_1</var>, <var class="var">expr_2</var>, …)</code> and may occur anywhere a function call is legitimate. </p> <ul class="mini-toc"> <li><a href="#Simple-examples" accesskey="1">Simple examples</a></li> <li><a href="#Defining-new-binary-operators" accesskey="2">Defining new binary operators</a></li> <li><a href="#Named-arguments-and-defaults" accesskey="3">Named arguments and defaults</a></li> <li><a href="#The-three-dots-argument" accesskey="4">The ‘<samp class="samp">…</samp>’ argument</a></li> <li><a href="#Assignment-within-functions" accesskey="5">Assignments within functions</a></li> <li><a href="#More-advanced-examples" accesskey="6">More advanced examples</a></li> <li><a href="#Scope" accesskey="7">Scope</a></li> <li><a href="#Customizing-the-environment" accesskey="8">Customizing the environment</a></li> <li><a href="#Object-orientation" accesskey="9">Classes, generic functions and object orientation</a></li> </ul> <hr> <div class="section-level-extent" id="Simple-examples"> <div class="nav-panel"> <p> Next: <a href="#Defining-new-binary-operators" accesskey="n" rel="next">Defining new binary operators</a>, Previous: <a href="#Writing-your-own-functions" accesskey="p" rel="prev">Writing your own functions</a>, Up: <a href="#Writing-your-own-functions" accesskey="u" rel="up">Writing your own functions</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Simple-examples-1"><span>10.1 Simple examples<a class="copiable-link" href="#Simple-examples-1"> ¶</a></span></h3> <p>As a first example, consider a function to calculate the two sample <em class="math">t</em>-statistic, showing “all the steps”. This is an artificial example, of course, since there are other, simpler ways of achieving the same end. </p> <p>The function is defined as follows: </p> <div class="example"> <pre class="example-preformatted">> twosam <- function(y1, y2) { n1 <- length(y1); n2 <- length(y2) yb1 <- mean(y1); yb2 <- mean(y2) s1 <- var(y1); s2 <- var(y2) s <- ((n1-1)*s1 + (n2-1)*s2)/(n1+n2-2) tst <- (yb1 - yb2)/sqrt(s*(1/n1 + 1/n2)) tst } </pre></div> <p>With this function defined, you could perform two sample <em class="math">t</em>-tests using a call such as </p> <div class="example"> <pre class="example-preformatted">> tstat <- twosam(data$male, data$female); tstat </pre></div> <p>As a second example, consider a function to emulate directly the <small class="sc">MATLAB</small> backslash command, which returns the coefficients of the orthogonal projection of the vector <em class="math">y</em> onto the column space of the matrix, <em class="math">X</em>. (This is ordinarily called the least squares estimate of the regression coefficients.) This would ordinarily be done with the <code class="code">qr()</code> function; however this is sometimes a bit tricky to use directly and it pays to have a simple function such as the following to use it safely. </p> <p>Thus given a <em class="math">n</em> by <em class="math">1</em> vector <em class="math">y</em> and an <em class="math">n</em> by <em class="math">p</em> matrix <em class="math">X</em> then <em class="math">X \ y</em> is defined as (X’X)^{-}X’y, where (X’X)^{-} is a generalized inverse of <em class="math">X'X</em>. </p> <div class="example"> <pre class="example-preformatted">> bslash <- function(X, y) { X <- qr(X) qr.coef(X, y) } </pre></div> <p>After this object is created it may be used in statements such as </p> <div class="example"> <pre class="example-preformatted">> regcoeff <- bslash(Xmat, yvar) </pre></div> <p>and so on. </p> <p>The classical R function <code class="code">lsfit()</code> does this job quite well, and more<a class="footnote" id="DOCF21" href="#FOOT21"><sup>21</sup></a>. It in turn uses the functions <code class="code">qr()</code> and <code class="code">qr.coef()</code> in the slightly counterintuitive way above to do this part of the calculation. Hence there is probably some value in having just this part isolated in a simple to use function if it is going to be in frequent use. If so, we may wish to make it a matrix binary operator for even more convenient use. </p> <hr> </div> <div class="section-level-extent" id="Defining-new-binary-operators"> <div class="nav-panel"> <p> Next: <a href="#Named-arguments-and-defaults" accesskey="n" rel="next">Named arguments and defaults</a>, Previous: <a href="#Simple-examples" accesskey="p" rel="prev">Simple examples</a>, Up: <a href="#Writing-your-own-functions" accesskey="u" rel="up">Writing your own functions</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Defining-new-binary-operators-1"><span>10.2 Defining new binary operators<a class="copiable-link" href="#Defining-new-binary-operators-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Binary-operators"></a> <p>Had we given the <code class="code">bslash()</code> function a different name, namely one of the form </p> <div class="example"> <pre class="example-preformatted">%<var class="var">anything</var>% </pre></div> <p>it could have been used as a <em class="emph">binary operator</em> in expressions rather than in function form. Suppose, for example, we choose <code class="code">!</code> for the internal character. The function definition would then start as </p> <div class="example"> <pre class="example-preformatted">> "%!%" <- function(X, y) { ... } </pre></div> <p>(Note the use of quote marks.) The function could then be used as <code class="code">X %!% y</code>. (The backslash symbol itself is not a convenient choice as it presents special problems in this context.) </p> <p>The matrix multiplication operator, <code class="code">%*%</code>, and the outer product matrix operator <code class="code">%o%</code> are other examples of binary operators defined in this way. </p> <hr> </div> <div class="section-level-extent" id="Named-arguments-and-defaults"> <div class="nav-panel"> <p> Next: <a href="#The-three-dots-argument" accesskey="n" rel="next">The ‘<samp class="samp">…</samp>’ argument</a>, Previous: <a href="#Defining-new-binary-operators" accesskey="p" rel="prev">Defining new binary operators</a>, Up: <a href="#Writing-your-own-functions" accesskey="u" rel="up">Writing your own functions</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Named-arguments-and-defaults-1"><span>10.3 Named arguments and defaults<a class="copiable-link" href="#Named-arguments-and-defaults-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Named-arguments"></a> <a class="index-entry-id" id="index-Default-values"></a> <p>As first noted in <a class="ref" href="#Generating-regular-sequences">Generating regular sequences</a>, if arguments to called functions are given in the “<code class="code"><var class="var">name</var>=<var class="var">object</var></code>” form, they may be given in any order. Furthermore the argument sequence may begin in the unnamed, positional form, and specify named arguments after the positional arguments. </p> <p>Thus if there is a function <code class="code">fun1</code> defined by </p> <div class="example"> <pre class="example-preformatted">> fun1 <- function(data, data.frame, graph, limit) { <span class="r">[function body omitted]</span> } </pre></div> <p>then the function may be invoked in several ways, for example </p> <div class="example"> <pre class="example-preformatted">> ans <- fun1(d, df, TRUE, 20) > ans <- fun1(d, df, graph=TRUE, limit=20) > ans <- fun1(data=d, limit=20, graph=TRUE, data.frame=df) </pre></div> <p>are all equivalent. </p> <p>In many cases arguments can be given commonly appropriate default values, in which case they may be omitted altogether from the call when the defaults are appropriate. For example, if <code class="code">fun1</code> were defined as </p> <div class="example"> <pre class="example-preformatted">> fun1 <- function(data, data.frame, graph=TRUE, limit=20) { ... } </pre></div> <p>it could be called as </p> <div class="example"> <pre class="example-preformatted">> ans <- fun1(d, df) </pre></div> <p>which is now equivalent to the three cases above, or as </p> <div class="example"> <pre class="example-preformatted">> ans <- fun1(d, df, limit=10) </pre></div> <p>which changes one of the defaults. </p> <p>It is important to note that defaults may be arbitrary expressions, even involving other arguments to the same function; they are not restricted to be constants as in our simple example here. </p> <hr> </div> <div class="section-level-extent" id="The-three-dots-argument"> <div class="nav-panel"> <p> Next: <a href="#Assignment-within-functions" accesskey="n" rel="next">Assignments within functions</a>, Previous: <a href="#Named-arguments-and-defaults" accesskey="p" rel="prev">Named arguments and defaults</a>, Up: <a href="#Writing-your-own-functions" accesskey="u" rel="up">Writing your own functions</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="The-_2026-argument"><span>10.4 The ‘<samp class="samp">…</samp>’ argument<a class="copiable-link" href="#The-_2026-argument"> ¶</a></span></h3> <p>Another frequent requirement is to allow one function to pass on argument settings to another. For example many graphics functions use the function <code class="code">par()</code> and functions like <code class="code">plot()</code> allow the user to pass on graphical parameters to <code class="code">par()</code> to control the graphical output. (See <a class="xref" href="#The-par_0028_0029-function">Permanent changes: The <code class="code">par()</code> function</a>, for more details on the <code class="code">par()</code> function.) This can be done by including an extra argument, literally ‘<samp class="samp">…</samp>’, of the function, which may then be passed on. An outline example is given below. </p> <div class="example"> <pre class="example-preformatted">fun1 <- function(data, data.frame, graph=TRUE, limit=20, ...) { <span class="r">[omitted statements]</span> if (graph) par(pch="*", ...) <span class="r">[more omissions]</span> } </pre></div> <p>Less frequently, a function will need to refer to components of ‘<samp class="samp">…</samp>’. The expression <code class="code">list(...)</code> evaluates all such arguments and returns them in a named list, while <code class="code">..1</code>, <code class="code">..2</code>, etc. evaluate them one at a time, with ‘<samp class="samp">..n</samp>’ returning the n-th unmatched argument. </p> <hr> </div> <div class="section-level-extent" id="Assignment-within-functions"> <div class="nav-panel"> <p> Next: <a href="#More-advanced-examples" accesskey="n" rel="next">More advanced examples</a>, Previous: <a href="#The-three-dots-argument" accesskey="p" rel="prev">The ‘<samp class="samp">…</samp>’ argument</a>, Up: <a href="#Writing-your-own-functions" accesskey="u" rel="up">Writing your own functions</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Assignments-within-functions"><span>10.5 Assignments within functions<a class="copiable-link" href="#Assignments-within-functions"> ¶</a></span></h3> <p>Note that <em class="emph">any ordinary assignments done within the function are local and temporary and are lost after exit from the function</em>. Thus the assignment <code class="code">X <- qr(X)</code> does not affect the value of the argument in the calling program. </p> <p>To understand completely the rules governing the scope of R assignments the reader needs to be familiar with the notion of an evaluation <em class="emph">frame</em>. This is a somewhat advanced, though hardly difficult, topic and is not covered further here. </p> <p>If global and permanent assignments are intended within a function, then either the ‘superassignment’ operator, <code class="code"><<-</code> or the function <code class="code">assign()</code> can be used. See the <code class="code">help</code> document for details. </p> <hr> </div> <div class="section-level-extent" id="More-advanced-examples"> <div class="nav-panel"> <p> Next: <a href="#Scope" accesskey="n" rel="next">Scope</a>, Previous: <a href="#Assignment-within-functions" accesskey="p" rel="prev">Assignments within functions</a>, Up: <a href="#Writing-your-own-functions" accesskey="u" rel="up">Writing your own functions</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="More-advanced-examples-1"><span>10.6 More advanced examples<a class="copiable-link" href="#More-advanced-examples-1"> ¶</a></span></h3> <ul class="mini-toc"> <li><a href="#Efficiency-factors-in-block-designs" accesskey="1">Efficiency factors in block designs</a></li> <li><a href="#Dropping-all-names-in-a-printed-array" accesskey="2">Dropping all names in a printed array</a></li> <li><a href="#Recursive-numerical-integration" accesskey="3">Recursive numerical integration</a></li> </ul> <hr> <div class="subsection-level-extent" id="Efficiency-factors-in-block-designs"> <div class="nav-panel"> <p> Next: <a href="#Dropping-all-names-in-a-printed-array" accesskey="n" rel="next">Dropping all names in a printed array</a>, Previous: <a href="#More-advanced-examples" accesskey="p" rel="prev">More advanced examples</a>, Up: <a href="#More-advanced-examples" accesskey="u" rel="up">More advanced examples</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Efficiency-factors-in-block-designs-1"><span>10.6.1 Efficiency factors in block designs<a class="copiable-link" href="#Efficiency-factors-in-block-designs-1"> ¶</a></span></h4> <p>As a more complete, if a little pedestrian, example of a function, consider finding the efficiency factors for a block design. (Some aspects of this problem have already been discussed in <a class="ref" href="#Index-matrices">Index matrices</a>.) </p> <p>A block design is defined by two factors, say <code class="code">blocks</code> (<code class="code">b</code> levels) and <code class="code">varieties</code> (<code class="code">v</code> levels). If <em class="math">R</em> and <em class="math">K</em> are the <em class="math">v</em> by <em class="math">v</em> and <em class="math">b</em> by <em class="math">b</em> <em class="emph">replications</em> and <em class="emph">block size</em> matrices, respectively, and <em class="math">N</em> is the <em class="math">b</em> by <em class="math">v</em> incidence matrix, then the efficiency factors are defined as the eigenvalues of the matrix E = I_v - R^{-1/2}N’K^{-1}NR^{-1/2} = I_v - A’A, where A = K^{-1/2}NR^{-1/2}. One way to write the function is given below. </p> <div class="example"> <pre class="example-preformatted">> bdeff <- function(blocks, varieties) { blocks <- as.factor(blocks) # <span class="r">minor safety move</span> b <- length(levels(blocks)) varieties <- as.factor(varieties) # <span class="r">minor safety move</span> v <- length(levels(varieties)) K <- as.vector(table(blocks)) # <span class="r">remove dim attr</span> R <- as.vector(table(varieties)) # <span class="r">remove dim attr</span> N <- table(blocks, varieties) A <- 1/sqrt(K) * N * rep(1/sqrt(R), rep(b, v)) sv <- svd(A) list(eff=1 - sv$d^2, blockcv=sv$u, varietycv=sv$v) } </pre></div> <p>It is numerically slightly better to work with the singular value decomposition on this occasion rather than the eigenvalue routines. </p> <p>The result of the function is a list giving not only the efficiency factors as the first component, but also the block and variety canonical contrasts, since sometimes these give additional useful qualitative information. </p> <hr> </div> <div class="subsection-level-extent" id="Dropping-all-names-in-a-printed-array"> <div class="nav-panel"> <p> Next: <a href="#Recursive-numerical-integration" accesskey="n" rel="next">Recursive numerical integration</a>, Previous: <a href="#Efficiency-factors-in-block-designs" accesskey="p" rel="prev">Efficiency factors in block designs</a>, Up: <a href="#More-advanced-examples" accesskey="u" rel="up">More advanced examples</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Dropping-all-names-in-a-printed-array-1"><span>10.6.2 Dropping all names in a printed array<a class="copiable-link" href="#Dropping-all-names-in-a-printed-array-1"> ¶</a></span></h4> <p>For printing purposes with large matrices or arrays, it is often useful to print them in close block form without the array names or numbers. Removing the <code class="code">dimnames</code> attribute will not achieve this effect, but rather the array must be given a <code class="code">dimnames</code> attribute consisting of empty strings. For example to print a matrix, <code class="code">X</code> </p> <div class="example"> <pre class="example-preformatted">> temp <- X > dimnames(temp) <- list(rep("", nrow(X)), rep("", ncol(X))) > temp; rm(temp) </pre></div> <p>This can be much more conveniently done using a function, <code class="code">no.dimnames()</code>, shown below, as a “wrap around” to achieve the same result. It also illustrates how some effective and useful user functions can be quite short. </p> <div class="example"> <pre class="example-preformatted">no.dimnames <- function(a) { ## <span class="r">Remove all dimension names from an array for compact printing.</span> d <- list() l <- 0 for(i in dim(a)) { d[[l <- l + 1]] <- rep("", i) } dimnames(a) <- d a } </pre></div> <p>With this function defined, an array may be printed in close format using </p> <div class="example"> <pre class="example-preformatted">> no.dimnames(X) </pre></div> <p>This is particularly useful for large integer arrays, where patterns are the real interest rather than the values. </p> <hr> </div> <div class="subsection-level-extent" id="Recursive-numerical-integration"> <div class="nav-panel"> <p> Previous: <a href="#Dropping-all-names-in-a-printed-array" accesskey="p" rel="prev">Dropping all names in a printed array</a>, Up: <a href="#More-advanced-examples" accesskey="u" rel="up">More advanced examples</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Recursive-numerical-integration-1"><span>10.6.3 Recursive numerical integration<a class="copiable-link" href="#Recursive-numerical-integration-1"> ¶</a></span></h4> <p>Functions may be recursive, and may themselves define functions within themselves. Note, however, that such functions, or indeed variables, are not inherited by called functions in higher evaluation frames as they would be if they were on the search path. </p> <p>The example below shows a naive way of performing one-dimensional numerical integration. The integrand is evaluated at the end points of the range and in the middle. If the one-panel trapezium rule answer is close enough to the two panel, then the latter is returned as the value. Otherwise the same process is recursively applied to each panel. The result is an adaptive integration process that concentrates function evaluations in regions where the integrand is farthest from linear. There is, however, a heavy overhead, and the function is only competitive with other algorithms when the integrand is both smooth and very difficult to evaluate. </p> <p>The example is also given partly as a little puzzle in R programming. </p> <div class="example"> <pre class="example-preformatted">area <- function(f, a, b, eps = 1.0e-06, lim = 10) { fun1 <- function(f, a, b, fa, fb, a0, eps, lim, fun) { ## <span class="r">function ‘fun1’ is only visible inside ‘area’</span> d <- (a + b)/2 h <- (b - a)/4 fd <- f(d) a1 <- h * (fa + fd) a2 <- h * (fd + fb) if(abs(a0 - a1 - a2) < eps || lim == 0) return(a1 + a2) else { return(fun(f, a, d, fa, fd, a1, eps, lim - 1, fun) + fun(f, d, b, fd, fb, a2, eps, lim - 1, fun)) } } fa <- f(a) fb <- f(b) a0 <- ((fa + fb) * (b - a))/2 fun1(f, a, b, fa, fb, a0, eps, lim, fun1) } </pre></div> <hr> </div> </div> <div class="section-level-extent" id="Scope"> <div class="nav-panel"> <p> Next: <a href="#Customizing-the-environment" accesskey="n" rel="next">Customizing the environment</a>, Previous: <a href="#More-advanced-examples" accesskey="p" rel="prev">More advanced examples</a>, Up: <a href="#Writing-your-own-functions" accesskey="u" rel="up">Writing your own functions</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Scope-1"><span>10.7 Scope<a class="copiable-link" href="#Scope-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Scope"></a> <p>The discussion in this section is somewhat more technical than in other parts of this document. However, it details one of the major differences between <small class="sc">S-PLUS</small> and R. </p> <p>The symbols which occur in the body of a function can be divided into three classes; formal parameters, local variables and free variables. The formal parameters of a function are those occurring in the argument list of the function. Their values are determined by the process of <em class="emph">binding</em> the actual function arguments to the formal parameters. Local variables are those whose values are determined by the evaluation of expressions in the body of the functions. Variables which are not formal parameters or local variables are called free variables. Free variables become local variables if they are assigned to. Consider the following function definition. </p> <div class="example"> <pre class="example-preformatted">f <- function(x) { y <- 2*x print(x) print(y) print(z) } </pre></div> <p>In this function, <code class="code">x</code> is a formal parameter, <code class="code">y</code> is a local variable and <code class="code">z</code> is a free variable. </p> <p>In R the free variable bindings are resolved by first looking in the environment in which the function was created. This is called <em class="emph">lexical scope</em>. First we define a function called <code class="code">cube</code>. </p> <div class="example"> <pre class="example-preformatted">cube <- function(n) { sq <- function() n*n n*sq() } </pre></div> <p>The variable <code class="code">n</code> in the function <code class="code">sq</code> is not an argument to that function. Therefore it is a free variable and the scoping rules must be used to ascertain the value that is to be associated with it. Under static scope (<small class="sc">S-PLUS</small>) the value is that associated with a global variable named <code class="code">n</code>. Under lexical scope (R) it is the parameter to the function <code class="code">cube</code> since that is the active binding for the variable <code class="code">n</code> at the time the function <code class="code">sq</code> was defined. The difference between evaluation in R and evaluation in <small class="sc">S-PLUS</small> is that <small class="sc">S-PLUS</small> looks for a global variable called <code class="code">n</code> while R first looks for a variable called <code class="code">n</code> in the environment created when <code class="code">cube</code> was invoked. </p> <div class="example"> <pre class="example-preformatted">## <span class="r">first evaluation in S</span> S> cube(2) Error in sq(): Object "n" not found Dumped S> n <- 3 S> cube(2) [1] 18 ## <span class="r">then the same function evaluated in R</span> R> cube(2) [1] 8 </pre></div> <p>Lexical scope can also be used to give functions <em class="emph">mutable state</em>. In the following example we show how R can be used to mimic a bank account. A functioning bank account needs to have a balance or total, a function for making withdrawals, a function for making deposits and a function for stating the current balance. We achieve this by creating the three functions within <code class="code">account</code> and then returning a list containing them. When <code class="code">account</code> is invoked it takes a numerical argument <code class="code">total</code> and returns a list containing the three functions. Because these functions are defined in an environment which contains <code class="code">total</code>, they will have access to its value. </p> <p>The special assignment operator, <code class="code"><<-</code>, <a class="index-entry-id" id="index-_003c_003c_002d"></a> is used to change the value associated with <code class="code">total</code>. This operator looks back in enclosing environments for an environment that contains the symbol <code class="code">total</code> and when it finds such an environment it replaces the value, in that environment, with the value of right hand side. If the global or top-level environment is reached without finding the symbol <code class="code">total</code> then that variable is created and assigned to there. For most users <code class="code"><<-</code> creates a global variable and assigns the value of the right hand side to it<a class="footnote" id="DOCF22" href="#FOOT22"><sup>22</sup></a>. Only when <code class="code"><<-</code> has been used in a function that was returned as the value of another function will the special behavior described here occur. </p> <div class="example"> <pre class="example-preformatted">open.account <- function(total) { list( deposit = function(amount) { if(amount <= 0) stop("Deposits must be positive!\n") total <<- total + amount cat(amount, "deposited. Your balance is", total, "\n\n") }, withdraw = function(amount) { if(amount > total) stop("You don't have that much money!\n") total <<- total - amount cat(amount, "withdrawn. Your balance is", total, "\n\n") }, balance = function() { cat("Your balance is", total, "\n\n") } ) } ross <- open.account(100) robert <- open.account(200) ross$withdraw(30) ross$balance() robert$balance() ross$deposit(50) ross$balance() ross$withdraw(500) </pre></div> <hr> </div> <div class="section-level-extent" id="Customizing-the-environment"> <div class="nav-panel"> <p> Next: <a href="#Object-orientation" accesskey="n" rel="next">Classes, generic functions and object orientation</a>, Previous: <a href="#Scope" accesskey="p" rel="prev">Scope</a>, Up: <a href="#Writing-your-own-functions" accesskey="u" rel="up">Writing your own functions</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Customizing-the-environment-1"><span>10.8 Customizing the environment<a class="copiable-link" href="#Customizing-the-environment-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Customizing-the-environment"></a> <p>Users can customize their environment in several different ways. There is a site initialization file and every directory can have its own special initialization file. Finally, the special functions <code class="code">.First</code> and <code class="code">.Last</code> can be used. </p> <p>The location of the site initialization file is taken from the value of the <code class="env">R_PROFILE</code> environment variable. If that variable is unset, the file <samp class="file">Rprofile.site</samp> in the R home subdirectory <samp class="file">etc</samp> is used. This file should contain the commands that you want to execute every time R is started under your system. A second, personal, profile file named <samp class="file">.Rprofile</samp><a class="footnote" id="DOCF23" href="#FOOT23"><sup>23</sup></a> can be placed in any directory. If R is invoked in that directory then that file will be sourced. This file gives individual users control over their workspace and allows for different startup procedures in different working directories. If no <samp class="file">.Rprofile</samp> file is found in the startup directory, then R looks for a <samp class="file">.Rprofile</samp> file in the user’s home directory and uses that (if it exists). If the environment variable <code class="env">R_PROFILE_USER</code> is set, the file it points to is used instead of the <samp class="file">.Rprofile</samp> files. </p> <p>Any function named <code class="code">.First()</code> in either of the two profile files or in the <samp class="file">.RData</samp> image has a special status. It is automatically performed at the beginning of an R session and may be used to initialize the environment. For example, the definition in the example below alters the prompt to <code class="code">$</code> and sets up various other useful things that can then be taken for granted in the rest of the session. </p> <p>Thus, the sequence in which files are executed is, <samp class="file">Rprofile.site</samp>, the user profile, <samp class="file">.RData</samp> and then <code class="code">.First()</code>. A definition in later files will mask definitions in earlier files. </p> <div class="example"> <pre class="example-preformatted">> .First <- function() { options(prompt="$ ", continue="+\t") # <span class="r"><code class="code">$</code> is the prompt</span> options(digits=5, length=999) # <span class="r">custom numbers and printout</span> x11() # <span class="r">for graphics</span> par(pch = "+") # <span class="r">plotting character</span> source(file.path(Sys.getenv("HOME"), "R", "mystuff.R")) # <span class="r">my personal functions</span> library(MASS) # <span class="r">attach a package</span> } </pre></div> <a class="index-entry-id" id="index-_002eFirst"></a> <p>Similarly a function <code class="code">.Last()</code>, if defined, is (normally) executed at the very end of the session. An example is given below. </p> <div class="example"> <pre class="example-preformatted">> .Last <- function() { graphics.off() # <span class="r">a small safety measure.</span> cat(paste(date(),"\nAdios\n")) # <span class="r">Is it time for lunch?</span> } </pre></div> <a class="index-entry-id" id="index-_002eLast"></a> <hr> </div> <div class="section-level-extent" id="Object-orientation"> <div class="nav-panel"> <p> Previous: <a href="#Customizing-the-environment" accesskey="p" rel="prev">Customizing the environment</a>, Up: <a href="#Writing-your-own-functions" accesskey="u" rel="up">Writing your own functions</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Classes_002c-generic-functions-and-object-orientation"><span>10.9 Classes, generic functions and object orientation<a class="copiable-link" href="#Classes_002c-generic-functions-and-object-orientation"> ¶</a></span></h3> <a class="index-entry-id" id="index-Classes-1"></a> <a class="index-entry-id" id="index-Generic-functions"></a> <a class="index-entry-id" id="index-Object-orientation"></a> <p>The class of an object determines how it will be treated by what are known as <em class="emph">generic</em> functions. Put the other way round, a generic function performs a task or action on its arguments <em class="emph">specific to the class of the argument itself</em>. If the argument lacks any <code class="code">class</code> attribute, or has a class not catered for specifically by the generic function in question, there is always a <em class="emph">default action</em> provided. </p> <p>An example makes things clearer. The class mechanism offers the user the facility of designing and writing generic functions for special purposes. Among the other generic functions are <code class="code">plot()</code> for displaying objects graphically, <code class="code">summary()</code> for summarizing analyses of various types, and <code class="code">anova()</code> for comparing statistical models. </p> <p>The number of generic functions that can treat a class in a specific way can be quite large. For example, the functions that can accommodate in some fashion objects of class <code class="code">"data.frame"</code> include </p> <div class="example"> <pre class="example-preformatted">[ [[<- any as.matrix [<- mean plot summary </pre></div> <a class="index-entry-id" id="index-methods"></a> <p>A currently complete list can be got by using the <code class="code">methods()</code> function: </p> <div class="example"> <pre class="example-preformatted">> methods(class="data.frame") </pre></div> <p>Conversely the number of classes a generic function can handle can also be quite large. For example the <code class="code">plot()</code> function has a default method and variants for objects of classes <code class="code">"data.frame"</code>, <code class="code">"density"</code>, <code class="code">"factor"</code>, and more. A complete list can be got again by using the <code class="code">methods()</code> function: </p> <div class="example"> <pre class="example-preformatted">> methods(plot) </pre></div> <p>For many generic functions the function body is quite short, for example </p> <div class="example"> <pre class="example-preformatted">> coef function (object, ...) UseMethod("coef") </pre></div> <p>The presence of <code class="code">UseMethod</code> indicates this is a generic function. To see what methods are available we can use <code class="code">methods()</code> </p> <div class="example"> <pre class="example-preformatted">> methods(coef) [1] coef.aov* coef.Arima* coef.default* coef.listof* [5] coef.nls* coef.summary.nls* Non-visible functions are asterisked </pre></div> <p>In this example there are six methods, none of which can be seen by typing its name. We can read these by either of </p> <a class="index-entry-id" id="index-getAnywhere"></a> <a class="index-entry-id" id="index-getS3method"></a> <div class="example"> <pre class="example-preformatted">> getAnywhere("coef.aov") A single object matching ‘coef.aov’ was found It was found in the following places registered S3 method for coef from namespace stats namespace:stats with value function (object, ...) { z <- object$coef z[!is.na(z)] } > getS3method("coef", "aov") function (object, ...) { z <- object$coef z[!is.na(z)] } </pre></div> <p>A function named <code class="code"><var class="var">gen</var>.<var class="var">cl</var></code> will be invoked by the generic <code class="code"><var class="var">gen</var></code> for class <code class="code"><var class="var">cl</var></code>, so do not name functions in this style unless they are intended to be methods. </p> <p>The reader is referred to the <em class="emph">R Language Definition</em> for a more complete discussion of this mechanism. </p> <hr> </div> </div> <div class="chapter-level-extent" id="Statistical-models-in-R"> <div class="nav-panel"> <p> Next: <a href="#Graphics" accesskey="n" rel="next">Graphical procedures</a>, Previous: <a href="#Writing-your-own-functions" accesskey="p" rel="prev">Writing your own functions</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="chapter" id="Statistical-models-in-R-1"><span>11 Statistical models in R<a class="copiable-link" href="#Statistical-models-in-R-1"> ¶</a></span></h2> <a class="index-entry-id" id="index-Statistical-models"></a> <p>This section presumes the reader has some familiarity with statistical methodology, in particular with regression analysis and the analysis of variance. Later we make some rather more ambitious presumptions, namely that something is known about generalized linear models and nonlinear regression. </p> <p>The requirements for fitting statistical models are sufficiently well defined to make it possible to construct general tools that apply in a broad spectrum of problems. </p> <p>R provides an interlocking suite of facilities that make fitting statistical models very simple. As we mention in the introduction, the basic output is minimal, and one needs to ask for the details by calling extractor functions. </p> <ul class="mini-toc"> <li><a href="#Formulae-for-statistical-models" accesskey="1">Defining statistical models; formulae</a></li> <li><a href="#Linear-models" accesskey="2">Linear models</a></li> <li><a href="#Generic-functions-for-extracting-model-information" accesskey="3">Generic functions for extracting model information</a></li> <li><a href="#Analysis-of-variance-and-model-comparison" accesskey="4">Analysis of variance and model comparison</a></li> <li><a href="#Updating-fitted-models" accesskey="5">Updating fitted models</a></li> <li><a href="#Generalized-linear-models" accesskey="6">Generalized linear models</a></li> <li><a href="#Nonlinear-least-squares-and-maximum-likelihood-models" accesskey="7">Nonlinear least squares and maximum likelihood models</a></li> <li><a href="#Some-non_002dstandard-models" accesskey="8">Some non-standard models</a></li> </ul> <hr> <div class="section-level-extent" id="Formulae-for-statistical-models"> <div class="nav-panel"> <p> Next: <a href="#Linear-models" accesskey="n" rel="next">Linear models</a>, Previous: <a href="#Statistical-models-in-R" accesskey="p" rel="prev">Statistical models in R</a>, Up: <a href="#Statistical-models-in-R" accesskey="u" rel="up">Statistical models in R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Defining-statistical-models_003b-formulae"><span>11.1 Defining statistical models; formulae<a class="copiable-link" href="#Defining-statistical-models_003b-formulae"> ¶</a></span></h3> <a class="index-entry-id" id="index-Formulae"></a> <p>The template for a statistical model is a linear regression model with independent, homoscedastic errors </p> <div class="display"> <pre class="display-preformatted">y_i = sum_{j=0}^p beta_j x_{ij} + e_i, i = 1, ..., n, </pre></div> <p>where the e_i are NID(0, sigma^2). In matrix terms this would be written </p> <div class="display"> <pre class="display-preformatted">y = X beta + e </pre></div> <p>where the <em class="math">y</em> is the response vector, <em class="math">X</em> is the <em class="emph">model matrix</em> or <em class="emph">design matrix</em> and has columns <em class="math">x_0, x_1, ..., x_p</em>, the determining variables. Very often <em class="math">x_0</em> will be a column of ones defining an <em class="emph">intercept</em> term. </p> <h4 class="subsubheading" id="Examples"><span>Examples<a class="copiable-link" href="#Examples"> ¶</a></span></h4> <p>Before giving a formal specification, a few examples may usefully set the picture. </p> <p>Suppose <code class="code">y</code>, <code class="code">x</code>, <code class="code">x0</code>, <code class="code">x1</code>, <code class="code">x2</code>, … are numeric variables, <code class="code">X</code> is a matrix and <code class="code">A</code>, <code class="code">B</code>, <code class="code">C</code>, … are factors. The following formulae on the left side below specify statistical models as described on the right. </p> <dl class="table"> <dt><code class="code">y ~ x</code></dt> <dt><code class="code">y ~ 1 + x</code></dt> <dd><p>Both imply the same simple linear regression model of <em class="math">y</em> on <em class="math">x</em>. The first has an implicit intercept term, and the second an explicit one. </p> </dd> <dt><code class="code">y ~ 0 + x</code></dt> <dt><code class="code">y ~ -1 + x</code></dt> <dt><code class="code">y ~ x - 1</code></dt> <dd><p>Simple linear regression of <em class="math">y</em> on <em class="math">x</em> through the origin (that is, without an intercept term). </p> </dd> <dt><code class="code">log(y) ~ x1 + x2</code></dt> <dd><p>Multiple regression of the transformed variable,log(y), on <em class="math">x1</em> and <em class="math">x2</em> (with an implicit intercept term). </p> </dd> <dt><code class="code">y ~ poly(x,2)</code></dt> <dt><code class="code">y ~ 1 + x + I(x^2)</code></dt> <dd><p>Polynomial regression of <em class="math">y</em> on <em class="math">x</em> of degree 2. The first form uses orthogonal polynomials, and the second uses explicit powers, as basis. </p> </dd> <dt><code class="code">y ~ X + poly(x,2)</code></dt> <dd><p>Multiple regression <em class="math">y</em> with model matrix consisting of the matrix <em class="math">X</em> as well as polynomial terms in <em class="math">x</em> to degree 2. </p> </dd> <dt><code class="code">y ~ A</code></dt> <dd><p>Single classification analysis of variance model of <em class="math">y</em>, with classes determined by <em class="math">A</em>. </p> </dd> <dt><code class="code">y ~ A + x</code></dt> <dd><p>Single classification analysis of covariance model of <em class="math">y</em>, with classes determined by <em class="math">A</em>, and with covariate <em class="math">x</em>. </p> </dd> <dt><code class="code">y ~ A*B</code></dt> <dt><code class="code">y ~ A + B + A:B</code></dt> <dt><code class="code">y ~ B %in% A</code></dt> <dt><code class="code">y ~ A/B</code></dt> <dd><p>Two factor non-additive model of <em class="math">y</em> on <em class="math">A</em> and <em class="math">B</em>. The first two specify the same crossed classification and the second two specify the same nested classification. In abstract terms all four specify the same model subspace. </p> </dd> <dt><code class="code">y ~ (A + B + C)^2</code></dt> <dt><code class="code">y ~ A*B*C - A:B:C</code></dt> <dd><p>Three factor experiment but with a model containing main effects and two factor interactions only. Both formulae specify the same model. </p> </dd> <dt><code class="code">y ~ A * x</code></dt> <dt><code class="code">y ~ A/x</code></dt> <dt><code class="code">y ~ A/(1 + x) - 1</code></dt> <dd><p>Separate simple linear regression models of <em class="math">y</em> on <em class="math">x</em> within the levels of <em class="math">A</em>, with different codings. The last form produces explicit estimates of as many different intercepts and slopes as there are levels in <em class="math">A</em>. </p> </dd> <dt><code class="code">y ~ A*B + Error(C)</code></dt> <dd><p>An experiment with two treatment factors, <em class="math">A</em> and <em class="math">B</em>, and error strata determined by factor <em class="math">C</em>. For example a split plot experiment, with whole plots (and hence also subplots), determined by factor <em class="math">C</em>. </p></dd> </dl> <a class="index-entry-id" id="index-_007e"></a> <p>The operator <code class="code">~</code> is used to define a <em class="emph">model formula</em> in R. The form, for an ordinary linear model, is </p> <div class="example"> <pre class="example-preformatted"><var class="var">response</var> ~ <var class="var">op_1</var> <var class="var">term_1</var> <var class="var">op_2</var> <var class="var">term_2</var> <var class="var">op_3</var> <var class="var">term_3</var> <var class="var">...</var> </pre></div> <p>where </p> <dl class="table"> <dt><var class="var">response</var></dt> <dd><p>is a vector or matrix, (or expression evaluating to a vector or matrix) defining the response variable(s). </p></dd> <dt><var class="var">op_i</var></dt> <dd><p>is an operator, either <code class="code">+</code> or <code class="code">-</code>, implying the inclusion or exclusion of a term in the model, (the first is optional). </p></dd> <dt><var class="var">term_i</var></dt> <dd><p>is either </p><ul class="itemize mark-bullet"> <li>a vector or matrix expression, or <code class="code">1</code>, </li><li>a factor, or </li><li>a <em class="emph">formula expression</em> consisting of factors, vectors or matrices connected by <em class="emph">formula operators</em>. </li></ul> <p>In all cases each term defines a collection of columns either to be added to or removed from the model matrix. A <code class="code">1</code> stands for an intercept column and is by default included in the model matrix unless explicitly removed. </p> </dd> </dl> <p>The <em class="emph">formula operators</em> are similar in effect to the Wilkinson and Rogers notation used by such programs as Glim and Genstat. One inevitable change is that the operator ‘<samp class="samp"><code class="code">.</code></samp>’ becomes ‘<samp class="samp"><code class="code">:</code></samp>’ since the period is a valid name character in R. </p> <p>The notation is summarized below (based on Chambers & Hastie, 1992, p.29): </p> <dl class="table"> <dt><code class="code"><var class="var">Y</var> ~ <var class="var">M</var></code></dt> <dd><p><var class="var">Y</var> is modeled as <var class="var">M</var>. </p> </dd> <dt><code class="code"><var class="var">M_1</var> + <var class="var">M_2</var></code></dt> <dd><p>Include <var class="var">M_1</var> and <var class="var">M_2</var>. </p> </dd> <dt><code class="code"><var class="var">M_1</var> - <var class="var">M_2</var></code></dt> <dd><p>Include <var class="var">M_1</var> leaving out terms of <var class="var">M_2</var>. </p> </dd> <dt><code class="code"><var class="var">M_1</var> : <var class="var">M_2</var></code></dt> <dd><p>The tensor product of <var class="var">M_1</var> and <var class="var">M_2</var>. If both terms are factors, then the “subclasses” factor. </p> </dd> <dt><code class="code"><var class="var">M_1</var> %in% <var class="var">M_2</var></code></dt> <dd><p>Similar to <code class="code"><var class="var">M_1</var>:<var class="var">M_2</var></code>, but with a different coding. </p> </dd> <dt><code class="code"><var class="var">M_1</var> * <var class="var">M_2</var></code></dt> <dd><p><code class="code"><var class="var">M_1</var> + <var class="var">M_2</var> + <var class="var">M_1</var>:<var class="var">M_2</var></code>. </p> </dd> <dt><code class="code"><var class="var">M_1</var> / <var class="var">M_2</var></code></dt> <dd><p><code class="code"><var class="var">M_1</var> + <var class="var">M_2</var> %in% <var class="var">M_1</var></code>. </p> </dd> <dt><code class="code"><var class="var">M</var>^<var class="var">n</var></code></dt> <dd><p>All terms in <var class="var">M</var> together with “interactions” up to order <var class="var">n</var> </p> </dd> <dt><code class="code">I(<var class="var">M</var>)</code></dt> <dd><p>Insulate <var class="var">M</var>. Inside <var class="var">M</var> all operators have their normal arithmetic meaning, and that term appears in the model matrix. </p></dd> </dl> <p>Note that inside the parentheses that usually enclose function arguments all operators have their normal arithmetic meaning. The function <code class="code">I()</code> is an identity function used to allow terms in model formulae to be defined using arithmetic operators. </p> <p>Note particularly that the model formulae specify the <em class="emph">columns of the model matrix</em>, the specification of the parameters being implicit. This is not the case in other contexts, for example in specifying nonlinear models. </p> <ul class="mini-toc"> <li><a href="#Contrasts" accesskey="1">Contrasts</a></li> </ul> <hr> <div class="subsection-level-extent" id="Contrasts"> <div class="nav-panel"> <p> Previous: <a href="#Formulae-for-statistical-models" accesskey="p" rel="prev">Defining statistical models; formulae</a>, Up: <a href="#Formulae-for-statistical-models" accesskey="u" rel="up">Defining statistical models; formulae</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Contrasts-1"><span>11.1.1 Contrasts<a class="copiable-link" href="#Contrasts-1"> ¶</a></span></h4> <a class="index-entry-id" id="index-Contrasts"></a> <p>We need at least some idea how the model formulae specify the columns of the model matrix. This is easy if we have continuous variables, as each provides one column of the model matrix (and the intercept will provide a column of ones if included in the model). </p> <a class="index-entry-id" id="index-Factors-1"></a> <a class="index-entry-id" id="index-Ordered-factors-1"></a> <p>What about a <em class="math">k</em>-level factor <code class="code">A</code>? The answer differs for unordered and ordered factors. For <em class="emph">unordered</em> factors <em class="math">k - 1</em> columns are generated for the indicators of the second, …, <em class="math">k</em>-th levels of the factor. (Thus the implicit parameterization is to contrast the response at each level with that at the first.) For <em class="emph">ordered</em> factors the <em class="math">k - 1</em> columns are the orthogonal polynomials on <em class="math">1, ..., k</em>, omitting the constant term. </p> <p>Although the answer is already complicated, it is not the whole story. First, if the intercept is omitted in a model that contains a factor term, the first such term is encoded into <em class="math">k</em> columns giving the indicators for all the levels. Second, the whole behavior can be changed by the <code class="code">options</code> setting for <code class="code">contrasts</code>. The default setting in R is </p> <div class="example"> <pre class="example-preformatted">options(contrasts = c("contr.treatment", "contr.poly")) </pre></div> <p>The main reason for mentioning this is that R and S have different defaults for unordered factors, S using Helmert contrasts. So if you need to compare your results to those of a textbook or paper which used <small class="sc">S-PLUS</small>, you will need to set </p> <div class="example"> <pre class="example-preformatted">options(contrasts = c("contr.helmert", "contr.poly")) </pre></div> <p>This is a deliberate difference, as treatment contrasts (R’s default) are thought easier for newcomers to interpret. </p> <p>We have still not finished, as the contrast scheme to be used can be set for each term in the model using the functions <code class="code">contrasts</code> and <code class="code">C</code>. <a class="index-entry-id" id="index-contrasts"></a> <a class="index-entry-id" id="index-C"></a> </p> <p>We have not yet considered interaction terms: these generate the products of the columns introduced for their component terms. </p> <p>Although the details are complicated, model formulae in R will normally generate the models that an expert statistician would expect, provided that marginality is preserved. Fitting, for example, a model with an interaction but not the corresponding main effects will in general lead to surprising results, and is for experts only. </p> <hr> </div> </div> <div class="section-level-extent" id="Linear-models"> <div class="nav-panel"> <p> Next: <a href="#Generic-functions-for-extracting-model-information" accesskey="n" rel="next">Generic functions for extracting model information</a>, Previous: <a href="#Formulae-for-statistical-models" accesskey="p" rel="prev">Defining statistical models; formulae</a>, Up: <a href="#Statistical-models-in-R" accesskey="u" rel="up">Statistical models in R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Linear-models-1"><span>11.2 Linear models<a class="copiable-link" href="#Linear-models-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Linear-models"></a> <p>The basic function for fitting ordinary multiple models is <code class="code">lm()</code>, and a streamlined version of the call is as follows: <a class="index-entry-id" id="index-lm"></a> </p> <div class="example"> <pre class="example-preformatted">> <var class="var">fitted.model</var> <- lm(<var class="var">formula</var>, data = <var class="var">data.frame</var>) </pre></div> <p>For example </p> <div class="example"> <pre class="example-preformatted">> fm2 <- lm(y ~ x1 + x2, data = production) </pre></div> <p>would fit a multiple regression model of <em class="math">y</em> on <em class="math">x1</em> and <em class="math">x2</em> (with implicit intercept term). </p> <p>The important (but technically optional) parameter <code class="code">data = production</code> specifies that any variables needed to construct the model should come first from the <code class="code">production</code> <em class="emph">data frame</em>. <em class="emph">This is the case regardless of whether data frame <code class="code">production</code> has been attached on the search path or not</em>. </p> <hr> </div> <div class="section-level-extent" id="Generic-functions-for-extracting-model-information"> <div class="nav-panel"> <p> Next: <a href="#Analysis-of-variance-and-model-comparison" accesskey="n" rel="next">Analysis of variance and model comparison</a>, Previous: <a href="#Linear-models" accesskey="p" rel="prev">Linear models</a>, Up: <a href="#Statistical-models-in-R" accesskey="u" rel="up">Statistical models in R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Generic-functions-for-extracting-model-information-1"><span>11.3 Generic functions for extracting model information<a class="copiable-link" href="#Generic-functions-for-extracting-model-information-1"> ¶</a></span></h3> <p>The value of <code class="code">lm()</code> is a fitted model object; technically a list of results of class <code class="code">"lm"</code>. Information about the fitted model can then be displayed, extracted, plotted and so on by using generic functions that orient themselves to objects of class <code class="code">"lm"</code>. These include </p> <div class="example"> <pre class="example-preformatted">add1 deviance formula predict step alias drop1 kappa print summary anova effects labels proj vcov coef family plot residuals </pre></div> <p>A brief description of the most commonly used ones is given below. </p> <dl class="table"> <dt><a id="index-anova"></a><span><code class="code">anova(<var class="var">object_1</var>, <var class="var">object_2</var>)</code><a class="copiable-link" href="#index-anova"> ¶</a></span></dt> <dd><p>Compare a submodel with an outer model and produce an analysis of variance table. </p> </dd> <dt><a class="index-entry-id" id="index-coef"></a> <a id="index-coefficients"></a><span><code class="code">coef(<var class="var">object</var>)</code><a class="copiable-link" href="#index-coefficients"> ¶</a></span></dt> <dd><p>Extract the regression coefficient (matrix). </p> <p>Long form: <code class="code">coefficients(<var class="var">object</var>)</code>. </p> </dd> <dt><a id="index-deviance"></a><span><code class="code">deviance(<var class="var">object</var>)</code><a class="copiable-link" href="#index-deviance"> ¶</a></span></dt> <dd><p>Residual sum of squares, weighted if appropriate. </p> </dd> <dt><a id="index-formula"></a><span><code class="code">formula(<var class="var">object</var>)</code><a class="copiable-link" href="#index-formula"> ¶</a></span></dt> <dd><p>Extract the model formula. </p> </dd> <dt><a id="index-plot"></a><span><code class="code">plot(<var class="var">object</var>)</code><a class="copiable-link" href="#index-plot"> ¶</a></span></dt> <dd><p>Produce four plots, showing residuals, fitted values and some diagnostics. </p> </dd> <dt><a id="index-predict"></a><span><code class="code">predict(<var class="var">object</var>, newdata=<var class="var">data.frame</var>)</code><a class="copiable-link" href="#index-predict"> ¶</a></span></dt> <dd><p>The data frame supplied must have variables specified with the same labels as the original. The value is a vector or matrix of predicted values corresponding to the determining variable values in <var class="var">data.frame</var>. </p> </dd> <dt><a id="index-print"></a><span><code class="code">print(<var class="var">object</var>)</code><a class="copiable-link" href="#index-print"> ¶</a></span></dt> <dd><p>Print a concise version of the object. Most often used implicitly. </p> </dd> <dt><a class="index-entry-id" id="index-resid"></a> <a id="index-residuals"></a><span><code class="code">residuals(<var class="var">object</var>)</code><a class="copiable-link" href="#index-residuals"> ¶</a></span></dt> <dd><p>Extract the (matrix of) residuals, weighted as appropriate. </p> <p>Short form: <code class="code">resid(<var class="var">object</var>)</code>. </p> </dd> <dt><a id="index-step"></a><span><code class="code">step(<var class="var">object</var>)</code><a class="copiable-link" href="#index-step"> ¶</a></span></dt> <dd><p>Select a suitable model by adding or dropping terms and preserving hierarchies. The model with the smallest value of AIC (Akaike’s An Information Criterion) discovered in the stepwise search is returned. </p> </dd> <dt><a id="index-summary-1"></a><span><code class="code">summary(<var class="var">object</var>)</code><a class="copiable-link" href="#index-summary-1"> ¶</a></span></dt> <dd><p>Print a comprehensive summary of the results of the regression analysis. </p> </dd> <dt><a id="index-vcov"></a><span><code class="code">vcov(<var class="var">object</var>)</code><a class="copiable-link" href="#index-vcov"> ¶</a></span></dt> <dd><p>Returns the variance-covariance matrix of the main parameters of a fitted model object. </p></dd> </dl> <hr> </div> <div class="section-level-extent" id="Analysis-of-variance-and-model-comparison"> <div class="nav-panel"> <p> Next: <a href="#Updating-fitted-models" accesskey="n" rel="next">Updating fitted models</a>, Previous: <a href="#Generic-functions-for-extracting-model-information" accesskey="p" rel="prev">Generic functions for extracting model information</a>, Up: <a href="#Statistical-models-in-R" accesskey="u" rel="up">Statistical models in R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Analysis-of-variance-and-model-comparison-1"><span>11.4 Analysis of variance and model comparison<a class="copiable-link" href="#Analysis-of-variance-and-model-comparison-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Analysis-of-variance"></a> <p>The model fitting function <code class="code">aov(<var class="var">formula</var>, data=<var class="var">data.frame</var>)</code> <a class="index-entry-id" id="index-aov"></a> operates at the simplest level in a very similar way to the function <code class="code">lm()</code>, and most of the generic functions listed in the table in <a class="ref" href="#Generic-functions-for-extracting-model-information">Generic functions for extracting model information</a> apply. </p> <p>It should be noted that in addition <code class="code">aov()</code> allows an analysis of models with multiple error strata such as split plot experiments, or balanced incomplete block designs with recovery of inter-block information. The model formula </p> <div class="example"> <pre class="example-preformatted"><var class="var">response</var> ~ <var class="var">mean.formula</var> + Error(<var class="var">strata.formula</var>) </pre></div> <a class="index-entry-id" id="index-Error"></a> <p>specifies a multi-stratum experiment with error strata defined by the <var class="var">strata.formula</var>. In the simplest case, <var class="var">strata.formula</var> is simply a factor, when it defines a two strata experiment, namely between and within the levels of the factor. </p> <p>For example, with all determining variables factors, a model formula such as that in: </p> <div class="example"> <pre class="example-preformatted">> fm <- aov(yield ~ v + n*p*k + Error(farms/blocks), data=farm.data) </pre></div> <p>would typically be used to describe an experiment with mean model <code class="code">v + n*p*k</code> and three error strata, namely “between farms”, “within farms, between blocks” and “within blocks”. </p> <ul class="mini-toc"> <li><a href="#ANOVA-tables" accesskey="1">ANOVA tables</a></li> </ul> <hr> <div class="subsection-level-extent" id="ANOVA-tables"> <div class="nav-panel"> <p> Previous: <a href="#Analysis-of-variance-and-model-comparison" accesskey="p" rel="prev">Analysis of variance and model comparison</a>, Up: <a href="#Analysis-of-variance-and-model-comparison" accesskey="u" rel="up">Analysis of variance and model comparison</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="ANOVA-tables-1"><span>11.4.1 ANOVA tables<a class="copiable-link" href="#ANOVA-tables-1"> ¶</a></span></h4> <p>Note also that the analysis of variance table (or tables) are for a sequence of fitted models. The sums of squares shown are the decrease in the residual sums of squares resulting from an inclusion of <em class="emph">that term</em> in the model at <em class="emph">that place</em> in the sequence. Hence only for orthogonal experiments will the order of inclusion be inconsequential. </p> <p>For multistratum experiments the procedure is first to project the response onto the error strata, again in sequence, and to fit the mean model to each projection. For further details, see Chambers & Hastie (1992). </p> <p>A more flexible alternative to the default full ANOVA table is to compare two or more models directly using the <code class="code">anova()</code> function. <a class="index-entry-id" id="index-anova-1"></a> </p> <div class="example"> <pre class="example-preformatted">> anova(<var class="var">fitted.model.1</var>, <var class="var">fitted.model.2</var>, ...) </pre></div> <p>The display is then an ANOVA table showing the differences between the fitted models when fitted in sequence. The fitted models being compared would usually be an hierarchical sequence, of course. This does not give different information to the default, but rather makes it easier to comprehend and control. </p> <hr> </div> </div> <div class="section-level-extent" id="Updating-fitted-models"> <div class="nav-panel"> <p> Next: <a href="#Generalized-linear-models" accesskey="n" rel="next">Generalized linear models</a>, Previous: <a href="#Analysis-of-variance-and-model-comparison" accesskey="p" rel="prev">Analysis of variance and model comparison</a>, Up: <a href="#Statistical-models-in-R" accesskey="u" rel="up">Statistical models in R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Updating-fitted-models-1"><span>11.5 Updating fitted models<a class="copiable-link" href="#Updating-fitted-models-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Updating-fitted-models"></a> <p>The <code class="code">update()</code> function is largely a convenience function that allows a model to be fitted that differs from one previously fitted usually by just a few additional or removed terms. Its form is <a class="index-entry-id" id="index-update"></a> </p> <div class="example"> <pre class="example-preformatted">> <var class="var">new.model</var> <- update(<var class="var">old.model</var>, <var class="var">new.formula</var>) </pre></div> <p>In the <var class="var">new.formula</var> the special name consisting of a period, ‘<samp class="samp"><code class="code">.</code></samp>’, <a class="index-entry-id" id="index-_002e"></a> only, can be used to stand for “the corresponding part of the old model formula”. For example, </p> <div class="example"> <pre class="example-preformatted">> fm05 <- lm(y ~ x1 + x2 + x3 + x4 + x5, data = production) > fm6 <- update(fm05, . ~ . + x6) > smf6 <- update(fm6, sqrt(.) ~ .) </pre></div> <p>would fit a five variate multiple regression with variables (presumably) from the data frame <code class="code">production</code>, fit an additional model including a sixth regressor variable, and fit a variant on the model where the response had a square root transform applied. </p> <p>Note especially that if the <code class="code">data=</code> argument is specified on the original call to the model fitting function, this information is passed on through the fitted model object to <code class="code">update()</code> and its allies. </p> <p>The name ‘<samp class="samp">.</samp>’ can also be used in other contexts, but with slightly different meaning. For example </p> <div class="example"> <pre class="example-preformatted">> fmfull <- lm(y ~ . , data = production) </pre></div> <p>would fit a model with response <code class="code">y</code> and regressor variables <em class="emph">all other variables in the data frame <code class="code">production</code></em>. </p> <p>Other functions for exploring incremental sequences of models are <code class="code">add1()</code>, <code class="code">drop1()</code> and <code class="code">step()</code>. <a class="index-entry-id" id="index-add1"></a> <a class="index-entry-id" id="index-drop1"></a> <a class="index-entry-id" id="index-step-1"></a> The names of these give a good clue to their purpose, but for full details see the on-line help. </p> <hr> </div> <div class="section-level-extent" id="Generalized-linear-models"> <div class="nav-panel"> <p> Next: <a href="#Nonlinear-least-squares-and-maximum-likelihood-models" accesskey="n" rel="next">Nonlinear least squares and maximum likelihood models</a>, Previous: <a href="#Updating-fitted-models" accesskey="p" rel="prev">Updating fitted models</a>, Up: <a href="#Statistical-models-in-R" accesskey="u" rel="up">Statistical models in R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Generalized-linear-models-1"><span>11.6 Generalized linear models<a class="copiable-link" href="#Generalized-linear-models-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Generalized-linear-models"></a> <p>Generalized linear modeling is a development of linear models to accommodate both non-normal response distributions and transformations to linearity in a clean and straightforward way. A generalized linear model may be described in terms of the following sequence of assumptions: </p> <ul class="itemize mark-bullet"> <li>There is a response, <em class="math">y</em>, of interest and stimulus variables x_1, x_2, …, whose values influence the distribution of the response. </li><li>The stimulus variables influence the distribution of <em class="math">y</em> through <em class="emph">a single linear function, only</em>. This linear function is called the <em class="emph">linear predictor</em>, and is usually written <div class="display"> <pre class="display-preformatted">eta = beta_1 x_1 + beta_2 x_2 + ... + beta_p x_p, </pre></div> <p>hence <em class="math">x_i</em> has no influence on the distribution of <em class="math">y</em> if and only if beta_i is zero. </p> </li><li>The distribution of <em class="math">y</em> is of the form <div class="display"> <pre class="display-preformatted">f_Y(y; mu, phi) = exp((A/phi) * (y lambda(mu) - gamma(lambda(mu))) + tau(y, phi)) </pre></div> <p>where phi is a <em class="emph">scale parameter</em> (possibly known), and is constant for all observations, <em class="math">A</em> represents a prior weight, assumed known but possibly varying with the observations, and mu is the mean of <em class="math">y</em>. </p> <p>So it is assumed that the distribution of <em class="math">y</em> is determined by its mean and possibly a scale parameter as well. </p> </li><li>The mean, mu, is a smooth invertible function of the linear predictor: <div class="display"> <pre class="display-preformatted">mu = m(eta), eta = m^{-1}(mu) = ell(mu) </pre></div> <p>and this inverse function, ell(), is called the <em class="emph">link function</em>. </p></li></ul> <p>These assumptions are loose enough to encompass a wide class of models useful in statistical practice, but tight enough to allow the development of a unified methodology of estimation and inference, at least approximately. The reader is referred to any of the current reference works on the subject for full details, such as McCullagh & Nelder (1989) or Dobson (1990). </p> <ul class="mini-toc"> <li><a href="#Families" accesskey="1">Families</a></li> <li><a href="#The-glm_0028_0029-function" accesskey="2">The <code class="code">glm()</code> function</a></li> </ul> <hr> <div class="subsection-level-extent" id="Families"> <div class="nav-panel"> <p> Next: <a href="#The-glm_0028_0029-function" accesskey="n" rel="next">The <code class="code">glm()</code> function</a>, Previous: <a href="#Generalized-linear-models" accesskey="p" rel="prev">Generalized linear models</a>, Up: <a href="#Generalized-linear-models" accesskey="u" rel="up">Generalized linear models</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Families-1"><span>11.6.1 Families<a class="copiable-link" href="#Families-1"> ¶</a></span></h4> <a class="index-entry-id" id="index-Families"></a> <p>The class of generalized linear models handled by facilities supplied in R includes <em class="emph">gaussian</em>, <em class="emph">binomial</em>, <em class="emph">poisson</em>, <em class="emph">inverse gaussian</em> and <em class="emph">gamma</em> response distributions and also <em class="emph">quasi-likelihood</em> models where the response distribution is not explicitly specified. In the latter case the <em class="emph">variance function</em> must be specified as a function of the mean, but in other cases this function is implied by the response distribution. </p> <p>Each response distribution admits a variety of link functions to connect the mean with the linear predictor. Those automatically available are shown in the following table: </p> <blockquote class="quotation"> <table summary="" class="multitable"> <thead><tr><th width="25%">Family name</th><th width="55%">Link functions</th></tr></thead> <tbody><tr><td width="25%"><code class="code">binomial</code></td><td width="55%"><code class="code">logit</code>, <code class="code">probit</code>, <code class="code">log</code>, <code class="code">cloglog</code></td></tr> <tr><td width="25%"><code class="code">gaussian</code></td><td width="55%"><code class="code">identity</code>, <code class="code">log</code>, <code class="code">inverse</code></td></tr> <tr><td width="25%"><code class="code">Gamma</code></td><td width="55%"><code class="code">identity</code>, <code class="code">inverse</code>, <code class="code">log</code></td></tr> <tr><td width="25%"><code class="code">inverse.gaussian</code></td><td width="55%"><code class="code">1/mu^2</code>, <code class="code">identity</code>, <code class="code">inverse</code>, <code class="code">log</code></td></tr> <tr><td width="25%"><code class="code">poisson</code></td><td width="55%"><code class="code">identity</code>, <code class="code">log</code>, <code class="code">sqrt</code></td></tr> <tr><td width="25%"><code class="code">quasi</code></td><td width="55%"><code class="code">logit</code>, <code class="code">probit</code>, <code class="code">cloglog</code>, <code class="code">identity</code>, <code class="code">inverse</code>, <code class="code">log</code>, <code class="code">1/mu^2</code>, <code class="code">sqrt</code></td></tr> </tbody> </table> </blockquote> <p>The combination of a response distribution, a link function and various other pieces of information that are needed to carry out the modeling exercise is called the <em class="emph">family</em> of the generalized linear model. </p> <hr> </div> <div class="subsection-level-extent" id="The-glm_0028_0029-function"> <div class="nav-panel"> <p> Previous: <a href="#Families" accesskey="p" rel="prev">Families</a>, Up: <a href="#Generalized-linear-models" accesskey="u" rel="up">Generalized linear models</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="The-glm_0028_0029-function-1"><span>11.6.2 The <code class="code">glm()</code> function<a class="copiable-link" href="#The-glm_0028_0029-function-1"> ¶</a></span></h4> <a class="index-entry-id" id="index-glm"></a> <p>Since the distribution of the response depends on the stimulus variables through a single linear function <em class="emph">only</em>, the same mechanism as was used for linear models can still be used to specify the linear part of a generalized model. The family has to be specified in a different way. </p> <p>The R function to fit a generalized linear model is <code class="code">glm()</code> which uses the form </p> <div class="example"> <pre class="example-preformatted">> <var class="var">fitted.model</var> <- glm(<var class="var">formula</var>, family=<var class="var">family.generator</var>, data=<var class="var">data.frame</var>) </pre></div> <p>The only new feature is the <var class="var">family.generator</var>, which is the instrument by which the family is described. It is the name of a function that generates a list of functions and expressions that together define and control the model and estimation process. Although this may seem a little complicated at first sight, its use is quite simple. </p> <p>The names of the standard, supplied family generators are given under “Family Name” in the table in <a class="ref" href="#Families">Families</a>. Where there is a choice of links, the name of the link may also be supplied with the family name, in parentheses as a parameter. In the case of the <code class="code">quasi</code> family, the variance function may also be specified in this way. </p> <p>Some examples make the process clear. </p> <h4 class="subsubheading" id="The-gaussian-family"><span>The <code class="code">gaussian</code> family<a class="copiable-link" href="#The-gaussian-family"> ¶</a></span></h4> <p>A call such as </p> <div class="example"> <pre class="example-preformatted">> fm <- glm(y ~ x1 + x2, family = gaussian, data = sales) </pre></div> <p>achieves the same result as </p> <div class="example"> <pre class="example-preformatted">> fm <- lm(y ~ x1+x2, data=sales) </pre></div> <p>but much less efficiently. Note how the gaussian family is not automatically provided with a choice of links, so no parameter is allowed. If a problem requires a gaussian family with a nonstandard link, this can usually be achieved through the <code class="code">quasi</code> family, as we shall see later. </p> <h4 class="subsubheading" id="The-binomial-family"><span>The <code class="code">binomial</code> family<a class="copiable-link" href="#The-binomial-family"> ¶</a></span></h4> <p>Consider a small, artificial example, from Silvey (1970). </p> <p>On the Aegean island of Kalythos the male inhabitants suffer from a congenital eye disease, the effects of which become more marked with increasing age. Samples of islander males of various ages were tested for blindness and the results recorded. The data is shown below: </p> <table summary="" class="multitable"> <tbody><tr><td>Age:</td><td>20</td><td>35</td><td>45</td><td>55</td><td>70</td></tr> <tr><td>No. tested:</td><td>50</td><td>50</td><td>50</td><td>50</td><td>50</td></tr> <tr><td>No. blind:</td><td> 6<!-- /@w --></td><td>17</td><td>26</td><td>37</td><td>44</td></tr> </tbody> </table> <p>The problem we consider is to fit both logistic and probit models to this data, and to estimate for each model the LD50, that is the age at which the chance of blindness for a male inhabitant is 50%. </p> <p>If <em class="math">y</em> is the number of blind at age <em class="math">x</em> and <em class="math">n</em> the number tested, both models have the form y ~ B(n, F(beta_0 + beta_1 x)) where for the probit case, F(z) = Phi(z) is the standard normal distribution function, and in the logit case (the default), F(z) = e^z/(1+e^z). In both cases the LD50 is LD50 = - beta_0/beta_1 that is, the point at which the argument of the distribution function is zero. </p> <p>The first step is to set the data up as a data frame </p> <div class="example"> <pre class="example-preformatted">> kalythos <- data.frame(x = c(20,35,45,55,70), n = rep(50,5), y = c(6,17,26,37,44)) </pre></div> <p>To fit a binomial model using <code class="code">glm()</code> there are three possibilities for the response: </p> <ul class="itemize mark-bullet"> <li>If the response is a <em class="emph">vector</em> it is assumed to hold <em class="emph">binary</em> data, and so must be a <em class="math">0/1</em> vector. </li><li>If the response is a <em class="emph">two-column matrix</em> it is assumed that the first column holds the number of successes for the trial and the second holds the number of failures. </li><li>If the response is a <em class="emph">factor</em>, its first level is taken as failure (0) and all other levels as ‘success’ (1). </li></ul> <p>Here we need the second of these conventions, so we add a matrix to our data frame: </p> <div class="example"> <pre class="example-preformatted">> kalythos$Ymat <- cbind(kalythos$y, kalythos$n - kalythos$y) </pre></div> <p>To fit the models we use </p> <div class="example"> <pre class="example-preformatted">> fmp <- glm(Ymat ~ x, family = binomial(link=probit), data = kalythos) > fml <- glm(Ymat ~ x, family = binomial, data = kalythos) </pre></div> <p>Since the logit link is the default the parameter may be omitted on the second call. To see the results of each fit we could use </p> <div class="example"> <pre class="example-preformatted">> summary(fmp) > summary(fml) </pre></div> <p>Both models fit (all too) well. To find the LD50 estimate we can use a simple function: </p> <div class="example"> <pre class="example-preformatted">> ld50 <- function(b) -b[1]/b[2] > ldp <- ld50(coef(fmp)); ldl <- ld50(coef(fml)); c(ldp, ldl) </pre></div> <p>The actual estimates from this data are 43.663 years and 43.601 years respectively. </p> <h4 class="subsubheading" id="Poisson-models"><span>Poisson models<a class="copiable-link" href="#Poisson-models"> ¶</a></span></h4> <p>With the Poisson family the default link is the <code class="code">log</code>, and in practice the major use of this family is to fit surrogate Poisson log-linear models to frequency data, whose actual distribution is often multinomial. This is a large and important subject we will not discuss further here. It even forms a major part of the use of non-gaussian generalized models overall. </p> <p>Occasionally genuinely Poisson data arises in practice and in the past it was often analyzed as gaussian data after either a log or a square-root transformation. As a graceful alternative to the latter, a Poisson generalized linear model may be fitted as in the following example: </p> <div class="example"> <pre class="example-preformatted">> fmod <- glm(y ~ A + B + x, family = poisson(link=sqrt), data = worm.counts) </pre></div> <h4 class="subsubheading" id="Quasi_002dlikelihood-models"><span>Quasi-likelihood models<a class="copiable-link" href="#Quasi_002dlikelihood-models"> ¶</a></span></h4> <p>For all families the variance of the response will depend on the mean and will have the scale parameter as a multiplier. The form of dependence of the variance on the mean is a characteristic of the response distribution; for example for the Poisson distribution Var(y) = mu. </p> <p>For quasi-likelihood estimation and inference the precise response distribution is not specified, but rather only a link function and the form of the variance function as it depends on the mean. Since quasi-likelihood estimation uses formally identical techniques to those for the gaussian distribution, this family provides a way of fitting gaussian models with non-standard link functions or variance functions, incidentally. </p> <p>For example, consider fitting the non-linear regression y = theta_1 z_1 / (z_2 - theta_2) + e which may be written alternatively as y = 1 / (beta_1 x_1 + beta_2 x_2) + e where x_1 = z_2/z_1, x_2 = -1/z_1, beta_1 = 1/theta_1, and beta_2 = theta_2/theta_1. Supposing a suitable data frame to be set up we could fit this non-linear regression as </p> <div class="example"> <pre class="example-preformatted">> nlfit <- glm(y ~ x1 + x2 - 1, family = quasi(link=inverse, variance=constant), data = biochem) </pre></div> <p>The reader is referred to the manual and the help document for further information, as needed. </p> <hr> </div> </div> <div class="section-level-extent" id="Nonlinear-least-squares-and-maximum-likelihood-models"> <div class="nav-panel"> <p> Next: <a href="#Some-non_002dstandard-models" accesskey="n" rel="next">Some non-standard models</a>, Previous: <a href="#Generalized-linear-models" accesskey="p" rel="prev">Generalized linear models</a>, Up: <a href="#Statistical-models-in-R" accesskey="u" rel="up">Statistical models in R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Nonlinear-least-squares-and-maximum-likelihood-models-1"><span>11.7 Nonlinear least squares and maximum likelihood models<a class="copiable-link" href="#Nonlinear-least-squares-and-maximum-likelihood-models-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Nonlinear-least-squares"></a> <p>Certain forms of nonlinear model can be fitted by Generalized Linear Models (<code class="code">glm()</code>). But in the majority of cases we have to approach the nonlinear curve fitting problem as one of nonlinear optimization. R’s nonlinear optimization routines are <code class="code">optim()</code>, <code class="code">nlm()</code> and <code class="code">nlminb()</code>, <a class="index-entry-id" id="index-nlm"></a> <a class="index-entry-id" id="index-optim"></a> <a class="index-entry-id" id="index-nlminb"></a> We seek the parameter values that minimize some index of lack-of-fit, and they do this by trying out various parameter values iteratively. Unlike linear regression for example, there is no guarantee that the procedure will converge on satisfactory estimates. All the methods require initial guesses about what parameter values to try, and convergence may depend critically upon the quality of the starting values. </p> <ul class="mini-toc"> <li><a href="#Least-squares" accesskey="1">Least squares</a></li> <li><a href="#Maximum-likelihood" accesskey="2">Maximum likelihood</a></li> </ul> <hr> <div class="subsection-level-extent" id="Least-squares"> <div class="nav-panel"> <p> Next: <a href="#Maximum-likelihood" accesskey="n" rel="next">Maximum likelihood</a>, Previous: <a href="#Nonlinear-least-squares-and-maximum-likelihood-models" accesskey="p" rel="prev">Nonlinear least squares and maximum likelihood models</a>, Up: <a href="#Nonlinear-least-squares-and-maximum-likelihood-models" accesskey="u" rel="up">Nonlinear least squares and maximum likelihood models</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Least-squares-1"><span>11.7.1 Least squares<a class="copiable-link" href="#Least-squares-1"> ¶</a></span></h4> <p>One way to fit a nonlinear model is by minimizing the sum of the squared errors (SSE) or residuals. This method makes sense if the observed errors could have plausibly arisen from a normal distribution. </p> <p>Here is an example from Bates & Watts (1988), page 51. The data are: </p> <div class="example"> <pre class="example-preformatted">> x <- c(0.02, 0.02, 0.06, 0.06, 0.11, 0.11, 0.22, 0.22, 0.56, 0.56, 1.10, 1.10) > y <- c(76, 47, 97, 107, 123, 139, 159, 152, 191, 201, 207, 200) </pre></div> <p>The fit criterion to be minimized is: </p> <div class="example"> <pre class="example-preformatted">> fn <- function(p) sum((y - (p[1] * x)/(p[2] + x))^2) </pre></div> <p>In order to do the fit we need initial estimates of the parameters. One way to find sensible starting values is to plot the data, guess some parameter values, and superimpose the model curve using those values. </p> <div class="example"> <pre class="example-preformatted">> plot(x, y) > xfit <- seq(.02, 1.1, .05) > yfit <- 200 * xfit/(0.1 + xfit) > lines(spline(xfit, yfit)) </pre></div> <p>We could do better, but these starting values of 200 and 0.1 seem adequate. Now do the fit: </p> <div class="example"> <pre class="example-preformatted">> out <- nlm(fn, p = c(200, 0.1), hessian = TRUE) </pre></div> <a class="index-entry-id" id="index-nlm-1"></a> <p>After the fitting, <code class="code">out$minimum</code> is the SSE, and <code class="code">out$estimate</code> are the least squares estimates of the parameters. To obtain the approximate standard errors (SE) of the estimates we do: </p> <div class="example"> <pre class="example-preformatted">> sqrt(diag(2*out$minimum/(length(y) - 2) * solve(out$hessian))) </pre></div> <p>The <code class="code">2</code> which is subtracted in the line above represents the number of parameters. A 95% confidence interval would be the parameter estimate +/- 1.96 SE. We can superimpose the least squares fit on a new plot: </p> <div class="example"> <pre class="example-preformatted">> plot(x, y) > xfit <- seq(.02, 1.1, .05) > yfit <- 212.68384222 * xfit/(0.06412146 + xfit) > lines(spline(xfit, yfit)) </pre></div> <p>The standard package <strong class="strong">stats</strong> provides much more extensive facilities for fitting non-linear models by least squares. The model we have just fitted is the Michaelis-Menten model, so we can use </p> <div class="example"> <pre class="example-preformatted">> df <- data.frame(x=x, y=y) > fit <- nls(y ~ SSmicmen(x, Vm, K), df) > fit Nonlinear regression model model: y ~ SSmicmen(x, Vm, K) data: df Vm K 212.68370711 0.06412123 residual sum-of-squares: 1195.449 > summary(fit) Formula: y ~ SSmicmen(x, Vm, K) Parameters: Estimate Std. Error t value Pr(>|t|) Vm 2.127e+02 6.947e+00 30.615 3.24e-11 K 6.412e-02 8.281e-03 7.743 1.57e-05 Residual standard error: 10.93 on 10 degrees of freedom Correlation of Parameter Estimates: Vm K 0.7651 </pre></div> <hr> </div> <div class="subsection-level-extent" id="Maximum-likelihood"> <div class="nav-panel"> <p> Previous: <a href="#Least-squares" accesskey="p" rel="prev">Least squares</a>, Up: <a href="#Nonlinear-least-squares-and-maximum-likelihood-models" accesskey="u" rel="up">Nonlinear least squares and maximum likelihood models</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Maximum-likelihood-1"><span>11.7.2 Maximum likelihood<a class="copiable-link" href="#Maximum-likelihood-1"> ¶</a></span></h4> <a class="index-entry-id" id="index-Maximum-likelihood"></a> <p>Maximum likelihood is a method of nonlinear model fitting that applies even if the errors are not normal. The method finds the parameter values which maximize the log likelihood, or equivalently which minimize the negative log-likelihood. Here is an example from Dobson (1990), pp. 108–111. This example fits a logistic model to dose-response data, which clearly could also be fit by <code class="code">glm()</code>. The data are: </p> <div class="example"> <pre class="example-preformatted">> x <- c(1.6907, 1.7242, 1.7552, 1.7842, 1.8113, 1.8369, 1.8610, 1.8839) > y <- c( 6, 13, 18, 28, 52, 53, 61, 60) > n <- c(59, 60, 62, 56, 63, 59, 62, 60) </pre></div> <p>The negative log-likelihood to minimize is: </p> <div class="example"> <pre class="example-preformatted">> fn <- function(p) sum( - (y*(p[1]+p[2]*x) - n*log(1+exp(p[1]+p[2]*x)) + log(choose(n, y)) )) </pre></div> <p>We pick sensible starting values and do the fit: </p> <div class="example"> <pre class="example-preformatted">> out <- nlm(fn, p = c(-50,20), hessian = TRUE) </pre></div> <a class="index-entry-id" id="index-nlm-2"></a> <p>After the fitting, <code class="code">out$minimum</code> is the negative log-likelihood, and <code class="code">out$estimate</code> are the maximum likelihood estimates of the parameters. To obtain the approximate <abbr class="abbr">SE</abbr>s of the estimates we do: </p> <div class="example"> <pre class="example-preformatted">> sqrt(diag(solve(out$hessian))) </pre></div> <p>A 95% confidence interval would be the parameter estimate +/- 1.96 SE. </p> <hr> </div> </div> <div class="section-level-extent" id="Some-non_002dstandard-models"> <div class="nav-panel"> <p> Previous: <a href="#Nonlinear-least-squares-and-maximum-likelihood-models" accesskey="p" rel="prev">Nonlinear least squares and maximum likelihood models</a>, Up: <a href="#Statistical-models-in-R" accesskey="u" rel="up">Statistical models in R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Some-non_002dstandard-models-1"><span>11.8 Some non-standard models<a class="copiable-link" href="#Some-non_002dstandard-models-1"> ¶</a></span></h3> <p>We conclude this chapter with just a brief mention of some of the other facilities available in R for special regression and data analysis problems. </p> <ul class="itemize mark-bullet"> <li><a class="index-entry-id" id="index-Mixed-models"></a> <strong class="strong">Mixed models.</strong> The recommended <a class="url" href="https://CRAN.R-project.org/package=nlme"><strong class="strong">nlme</strong></a> package provides functions <code class="code">lme()</code> and <code class="code">nlme()</code> <a class="index-entry-id" id="index-lme"></a> <a class="index-entry-id" id="index-nlme"></a> for linear and non-linear mixed-effects models, that is linear and non-linear regressions in which some of the coefficients correspond to random effects. These functions make heavy use of formulae to specify the models. </li><li><a class="index-entry-id" id="index-Local-approximating-regressions"></a> <strong class="strong">Local approximating regressions.</strong> The <code class="code">loess()</code> <a class="index-entry-id" id="index-loess"></a> function fits a nonparametric regression by using a locally weighted regression. Such regressions are useful for highlighting a trend in messy data or for data reduction to give some insight into a large data set. <p>Function <code class="code">loess</code> is in the standard package <strong class="strong">stats</strong>, together with code for projection pursuit regression. <a class="index-entry-id" id="index-loess-1"></a> </p> </li><li><a class="index-entry-id" id="index-Robust-regression"></a> <strong class="strong">Robust regression.</strong> There are several functions available for fitting regression models in a way resistant to the influence of extreme outliers in the data. Function <code class="code">lqs</code> <a class="index-entry-id" id="index-lqs"></a> in the recommended package <a class="url" href="https://CRAN.R-project.org/package=MASS"><strong class="strong">MASS</strong></a> provides state-of-art algorithms for highly-resistant fits. Less resistant but statistically more efficient methods are available in packages, for example function <code class="code">rlm</code> <a class="index-entry-id" id="index-rlm"></a> in package <a class="url" href="https://CRAN.R-project.org/package=MASS"><strong class="strong">MASS</strong></a>. </li><li><a class="index-entry-id" id="index-Additive-models"></a> <strong class="strong">Additive models.</strong> This technique aims to construct a regression function from smooth additive functions of the determining variables, usually one for each determining variable. Functions <code class="code">avas</code> and <code class="code">ace</code> <a class="index-entry-id" id="index-avas"></a> <a class="index-entry-id" id="index-ace"></a> in package <a class="url" href="https://CRAN.R-project.org/package=acepack"><strong class="strong">acepack</strong></a> and functions <code class="code">bruto</code> and <code class="code">mars</code> <a class="index-entry-id" id="index-bruto"></a> <a class="index-entry-id" id="index-mars"></a> in package <a class="url" href="https://CRAN.R-project.org/package=mda"><strong class="strong">mda</strong></a> provide some examples of these techniques in user-contributed packages to R. An extension is <strong class="strong">Generalized Additive Models</strong>, implemented in user-contributed packages <a class="url" href="https://CRAN.R-project.org/package=gam"><strong class="strong">gam</strong></a> and <a class="url" href="https://CRAN.R-project.org/package=mgcv"><strong class="strong">mgcv</strong></a>. </li><li><a class="index-entry-id" id="index-Tree_002dbased-models"></a> <strong class="strong">Tree-based models.</strong> Rather than seek an explicit global linear model for prediction or interpretation, tree-based models seek to bifurcate the data, recursively, at critical points of the determining variables in order to partition the data ultimately into groups that are as homogeneous as possible within, and as heterogeneous as possible between. The results often lead to insights that other data analysis methods tend not to yield. <p>Models are again specified in the ordinary linear model form. The model fitting function is <code class="code">tree()</code>, <a class="index-entry-id" id="index-tree"></a> but many other generic functions such as <code class="code">plot()</code> and <code class="code">text()</code> are well adapted to displaying the results of a tree-based model fit in a graphical way. </p> <p>Tree models are available in R <em class="emph">via</em> the user-contributed packages <a class="url" href="https://CRAN.R-project.org/package=rpart"><strong class="strong">rpart</strong></a> and <a class="url" href="https://CRAN.R-project.org/package=tree"><strong class="strong">tree</strong></a>. </p> </li></ul> <hr> </div> </div> <div class="chapter-level-extent" id="Graphics"> <div class="nav-panel"> <p> Next: <a href="#Packages" accesskey="n" rel="next">Packages</a>, Previous: <a href="#Statistical-models-in-R" accesskey="p" rel="prev">Statistical models in R</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="chapter" id="Graphical-procedures"><span>12 Graphical procedures<a class="copiable-link" href="#Graphical-procedures"> ¶</a></span></h2> <p>Graphical facilities are an important and extremely versatile component of the R environment. It is possible to use the facilities to display a wide variety of statistical graphs and also to build entirely new types of graph. </p> <p>The graphics facilities can be used in both interactive and batch modes, but in most cases, interactive use is more productive. Interactive use is also easy because at startup time R initiates a graphics <em class="emph">device driver</em> which opens a special <em class="emph">graphics window</em> for the display of interactive graphics. Although this is done automatically, it may useful to know that the command used is <code class="code">X11()</code> under UNIX, <code class="code">windows()</code> under Windows and <code class="code">quartz()</code> under macOS. A new device can always be opened by <code class="code">dev.new()</code>. </p> <p>Once the device driver is running, R plotting commands can be used to produce a variety of graphical displays and to create entirely new kinds of display. </p> <p>Plotting commands are divided into three basic groups: </p> <ul class="itemize mark-bullet"> <li><strong class="strong">High-level</strong> plotting functions create a new plot on the graphics device, possibly with axes, labels, titles and so on. </li><li><strong class="strong">Low-level</strong> plotting functions add more information to an existing plot, such as extra points, lines and labels. </li><li><strong class="strong">Interactive</strong> graphics functions allow you interactively add information to, or extract information from, an existing plot, using a pointing device such as a mouse. </li></ul> <p>In addition, R maintains a list of <em class="emph">graphical parameters</em> which can be manipulated to customize your plots. </p> <p>This manual only describes what are known as ‘base’ graphics. A separate graphics sub-system in package <strong class="strong">grid</strong> coexists with base – it is more powerful but harder to use. There is a recommended package <a class="url" href="https://CRAN.R-project.org/package=lattice"><strong class="strong">lattice</strong></a> which builds on <strong class="strong">grid</strong> and provides ways to produce multi-panel plots akin to those in the <em class="emph">Trellis</em> system in S. </p> <ul class="mini-toc"> <li><a href="#High_002dlevel-plotting-commands" accesskey="1">High-level plotting commands</a></li> <li><a href="#Low_002dlevel-plotting-commands" accesskey="2">Low-level plotting commands</a></li> <li><a href="#Interacting-with-graphics" accesskey="3">Interacting with graphics</a></li> <li><a href="#Using-graphics-parameters" accesskey="4">Using graphics parameters</a></li> <li><a href="#Graphics-parameters" accesskey="5">Graphics parameters list</a></li> <li><a href="#Device-drivers" accesskey="6">Device drivers</a></li> <li><a href="#Dynamic-graphics" accesskey="7">Dynamic graphics</a></li> </ul> <hr> <div class="section-level-extent" id="High_002dlevel-plotting-commands"> <div class="nav-panel"> <p> Next: <a href="#Low_002dlevel-plotting-commands" accesskey="n" rel="next">Low-level plotting commands</a>, Previous: <a href="#Graphics" accesskey="p" rel="prev">Graphical procedures</a>, Up: <a href="#Graphics" accesskey="u" rel="up">Graphical procedures</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="High_002dlevel-plotting-commands-1"><span>12.1 High-level plotting commands<a class="copiable-link" href="#High_002dlevel-plotting-commands-1"> ¶</a></span></h3> <p>High-level plotting functions are designed to generate a complete plot of the data passed as arguments to the function. Where appropriate, axes, labels and titles are automatically generated (unless you request otherwise.) High-level plotting commands always start a new plot, erasing the current plot if necessary. </p> <ul class="mini-toc"> <li><a href="#The-plot_0028_0029-function" accesskey="1">The <code class="code">plot()</code> function</a></li> <li><a href="#Displaying-multivariate-data" accesskey="2">Displaying multivariate data</a></li> <li><a href="#Display-graphics" accesskey="3">Display graphics</a></li> <li><a href="#Arguments-to-high_002dlevel-plotting-functions" accesskey="4">Arguments to high-level plotting functions</a></li> </ul> <hr> <div class="subsection-level-extent" id="The-plot_0028_0029-function"> <div class="nav-panel"> <p> Next: <a href="#Displaying-multivariate-data" accesskey="n" rel="next">Displaying multivariate data</a>, Previous: <a href="#High_002dlevel-plotting-commands" accesskey="p" rel="prev">High-level plotting commands</a>, Up: <a href="#High_002dlevel-plotting-commands" accesskey="u" rel="up">High-level plotting commands</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="The-plot_0028_0029-function-1"><span>12.1.1 The <code class="code">plot()</code> function<a class="copiable-link" href="#The-plot_0028_0029-function-1"> ¶</a></span></h4> <a class="index-entry-id" id="index-plot-1"></a> <p>One of the most frequently used plotting functions in R is the <code class="code">plot()</code> function. This is a <em class="emph">generic</em> function: the type of plot produced is dependent on the type or <em class="emph">class</em> of the first argument. </p> <dl class="table"> <dt><code class="code">plot(<var class="var">x</var>, <var class="var">y</var>)</code></dt> <dt><code class="code">plot(<var class="var">xy</var>)</code></dt> <dd><p>If <var class="var">x</var> and <var class="var">y</var> are vectors, <code class="code">plot(<var class="var">x</var>, <var class="var">y</var>)</code> produces a scatterplot of <var class="var">y</var> against <var class="var">x</var>. The same effect can be produced by supplying one argument (second form) as either a list containing two elements <var class="var">x</var> and <var class="var">y</var> or a two-column matrix. </p> </dd> <dt><code class="code">plot(<var class="var">x</var>)</code></dt> <dd><p>If <var class="var">x</var> is a time series, this produces a time-series plot. If <var class="var">x</var> is a numeric vector, it produces a plot of the values in the vector against their index in the vector. If <var class="var">x</var> is a complex vector, it produces a plot of imaginary versus real parts of the vector elements. </p> </dd> <dt><code class="code">plot(<var class="var">f</var>)</code></dt> <dt><code class="code">plot(<var class="var">f</var>, <var class="var">y</var>)</code></dt> <dd><p><var class="var">f</var> is a factor object, <var class="var">y</var> is a numeric vector. The first form generates a bar plot of <var class="var">f</var>; the second form produces boxplots of <var class="var">y</var> for each level of <var class="var">f</var>. </p> </dd> <dt><code class="code">plot(<var class="var">df</var>)</code></dt> <dt><code class="code">plot(~ <var class="var">expr</var>)</code></dt> <dt><code class="code">plot(<var class="var">y</var> ~ <var class="var">expr</var>)</code></dt> <dd><p><var class="var">df</var> is a data frame, <var class="var">y</var> is any object, <var class="var">expr</var> is a list of object names separated by ‘<code class="code">+</code>’ (e.g., <code class="code">a + b + c</code>). The first two forms produce distributional plots of the variables in a data frame (first form) or of a number of named objects (second form). The third form plots <var class="var">y</var> against every object named in <var class="var">expr</var>. </p></dd> </dl> <hr> </div> <div class="subsection-level-extent" id="Displaying-multivariate-data"> <div class="nav-panel"> <p> Next: <a href="#Display-graphics" accesskey="n" rel="next">Display graphics</a>, Previous: <a href="#The-plot_0028_0029-function" accesskey="p" rel="prev">The <code class="code">plot()</code> function</a>, Up: <a href="#High_002dlevel-plotting-commands" accesskey="u" rel="up">High-level plotting commands</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Displaying-multivariate-data-1"><span>12.1.2 Displaying multivariate data<a class="copiable-link" href="#Displaying-multivariate-data-1"> ¶</a></span></h4> <p>R provides two very useful functions for representing multivariate data. If <code class="code">X</code> is a numeric matrix or data frame, the command </p> <div class="example"> <pre class="example-preformatted">> pairs(X) </pre></div> <a class="index-entry-id" id="index-pairs"></a> <p>produces a pairwise scatterplot matrix of the variables defined by the columns of <code class="code">X</code>, that is, every column of <code class="code">X</code> is plotted against every other column of <code class="code">X</code> and the resulting <em class="math">n(n-1)</em> plots are arranged in a matrix with plot scales constant over the rows and columns of the matrix. </p> <p>When three or four variables are involved a <em class="emph">coplot</em> may be more enlightening. If <code class="code">a</code> and <code class="code">b</code> are numeric vectors and <code class="code">c</code> is a numeric vector or factor object (all of the same length), then the command </p> <div class="example"> <pre class="example-preformatted">> coplot(a ~ b | c) </pre></div> <a class="index-entry-id" id="index-coplot"></a> <p>produces a number of scatterplots of <code class="code">a</code> against <code class="code">b</code> for given values of <code class="code">c</code>. If <code class="code">c</code> is a factor, this simply means that <code class="code">a</code> is plotted against <code class="code">b</code> for every level of <code class="code">c</code>. When <code class="code">c</code> is numeric, it is divided into a number of <em class="emph">conditioning intervals</em> and for each interval <code class="code">a</code> is plotted against <code class="code">b</code> for values of <code class="code">c</code> within the interval. The number and position of intervals can be controlled with <code class="code">given.values=</code> argument to <code class="code">coplot()</code>—the function <code class="code">co.intervals()</code> is useful for selecting intervals. You can also use two <em class="emph">given</em> variables with a command like </p> <div class="example"> <pre class="example-preformatted">> coplot(a ~ b | c + d) </pre></div> <p>which produces scatterplots of <code class="code">a</code> against <code class="code">b</code> for every joint conditioning interval of <code class="code">c</code> and <code class="code">d</code>. </p> <p>The <code class="code">coplot()</code> and <code class="code">pairs()</code> function both take an argument <code class="code">panel=</code> which can be used to customize the type of plot which appears in each panel. The default is <code class="code">points()</code> to produce a scatterplot but by supplying some other low-level graphics function of two vectors <code class="code">x</code> and <code class="code">y</code> as the value of <code class="code">panel=</code> you can produce any type of plot you wish. An example panel function useful for coplots is <code class="code">panel.smooth()</code>. </p> <hr> </div> <div class="subsection-level-extent" id="Display-graphics"> <div class="nav-panel"> <p> Next: <a href="#Arguments-to-high_002dlevel-plotting-functions" accesskey="n" rel="next">Arguments to high-level plotting functions</a>, Previous: <a href="#Displaying-multivariate-data" accesskey="p" rel="prev">Displaying multivariate data</a>, Up: <a href="#High_002dlevel-plotting-commands" accesskey="u" rel="up">High-level plotting commands</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Display-graphics-1"><span>12.1.3 Display graphics<a class="copiable-link" href="#Display-graphics-1"> ¶</a></span></h4> <p>Other high-level graphics functions produce different types of plots. Some examples are: </p> <dl class="table"> <dt><a class="index-entry-id" id="index-qqline-1"></a> <a class="index-entry-id" id="index-qqplot"></a> <a id="index-qqnorm-1"></a><span><code class="code">qqnorm(x)</code><a class="copiable-link" href="#index-qqnorm-1"> ¶</a></span></dt> <dt><code class="code">qqline(x)</code></dt> <dt><code class="code">qqplot(x, y)</code></dt> <dd><p>Distribution-comparison plots. The first form plots the numeric vector <code class="code">x</code> against the expected Normal order scores (a normal scores plot) and the second adds a straight line to such a plot by drawing a line through the distribution and data quartiles. The third form plots the quantiles of <code class="code">x</code> against those of <code class="code">y</code> to compare their respective distributions. </p> </dd> <dt><a id="index-hist-1"></a><span><code class="code">hist(x)</code><a class="copiable-link" href="#index-hist-1"> ¶</a></span></dt> <dt><code class="code">hist(x, nclass=<var class="var">n</var>)</code></dt> <dt><code class="code">hist(x, breaks=<var class="var">b</var>, …)</code></dt> <dd><p>Produces a histogram of the numeric vector <code class="code">x</code>. A sensible number of classes is usually chosen, but a recommendation can be given with the <code class="code">nclass=</code> argument. Alternatively, the breakpoints can be specified exactly with the <code class="code">breaks=</code> argument. If the <code class="code">probability=TRUE</code> argument is given, the bars represent relative frequencies divided by bin width instead of counts. </p> </dd> <dt><a id="index-dotchart"></a><span><code class="code">dotchart(x, …)</code><a class="copiable-link" href="#index-dotchart"> ¶</a></span></dt> <dd><p>Constructs a dot chart of the data in <code class="code">x</code>. In a dot chart the <em class="math">y</em>-axis gives a labelling of the data in <code class="code">x</code> and the <em class="math">x</em>-axis gives its value. For example it allows easy visual selection of all data entries with values lying in specified ranges. </p> </dd> <dt><a class="index-entry-id" id="index-contour"></a> <a class="index-entry-id" id="index-persp"></a> <a id="index-image"></a><span><code class="code">image(x, y, z, …)</code><a class="copiable-link" href="#index-image"> ¶</a></span></dt> <dt><code class="code">contour(x, y, z, …)</code></dt> <dt><code class="code">persp(x, y, z, …)</code></dt> <dd><p>Plots of three variables. The <code class="code">image</code> plot draws a grid of rectangles using different colours to represent the value of <code class="code">z</code>, the <code class="code">contour</code> plot draws contour lines to represent the value of <code class="code">z</code>, and the <code class="code">persp</code> plot draws a 3D surface. </p></dd> </dl> <hr> </div> <div class="subsection-level-extent" id="Arguments-to-high_002dlevel-plotting-functions"> <div class="nav-panel"> <p> Previous: <a href="#Display-graphics" accesskey="p" rel="prev">Display graphics</a>, Up: <a href="#High_002dlevel-plotting-commands" accesskey="u" rel="up">High-level plotting commands</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Arguments-to-high_002dlevel-plotting-functions-1"><span>12.1.4 Arguments to high-level plotting functions<a class="copiable-link" href="#Arguments-to-high_002dlevel-plotting-functions-1"> ¶</a></span></h4> <p>There are a number of arguments which may be passed to high-level graphics functions, as follows: </p> <dl class="table"> <dt><code class="code">add=TRUE</code></dt> <dd><p>Forces the function to act as a low-level graphics function, superimposing the plot on the current plot (some functions only). </p> </dd> <dt><code class="code">axes=FALSE</code></dt> <dd><p>Suppresses generation of axes—useful for adding your own custom axes with the <code class="code">axis()</code> function. The default, <code class="code">axes=TRUE</code>, means include axes. </p> </dd> <dt><code class="code">log="x"</code></dt> <dt><code class="code">log="y"</code></dt> <dt><code class="code">log="xy"</code></dt> <dd><p>Causes the <em class="math">x</em>, <em class="math">y</em> or both axes to be logarithmic. This will work for many, but not all, types of plot. </p> </dd> <dt><code class="code">type=</code></dt> <dd><p>The <code class="code">type=</code> argument controls the type of plot produced, as follows: </p> <dl class="table"> <dt><code class="code">type="p"</code></dt> <dd><p>Plot individual points (the default) </p></dd> <dt><code class="code">type="l"</code></dt> <dd><p>Plot lines </p></dd> <dt><code class="code">type="b"</code></dt> <dd><p>Plot points connected by lines (<em class="emph">both</em>) </p></dd> <dt><code class="code">type="o"</code></dt> <dd><p>Plot points overlaid by lines </p></dd> <dt><code class="code">type="h"</code></dt> <dd><p>Plot vertical lines from points to the zero axis (<em class="emph">high-density</em>) </p></dd> <dt><code class="code">type="s"</code></dt> <dt><code class="code">type="S"</code></dt> <dd><p>Step-function plots. In the first form, the top of the vertical defines the point; in the second, the bottom. </p></dd> <dt><code class="code">type="n"</code></dt> <dd><p>No plotting at all. However axes are still drawn (by default) and the coordinate system is set up according to the data. Ideal for creating plots with subsequent low-level graphics functions. </p></dd> </dl> </dd> <dt><code class="code">xlab=<var class="var">string</var></code></dt> <dt><code class="code">ylab=<var class="var">string</var></code></dt> <dd><p>Axis labels for the <em class="math">x</em> and <em class="math">y</em> axes. Use these arguments to change the default labels, usually the names of the objects used in the call to the high-level plotting function. </p> </dd> <dt><code class="code">main=<var class="var">string</var></code></dt> <dd><p>Figure title, placed at the top of the plot in a large font. </p> </dd> <dt><code class="code">sub=<var class="var">string</var></code></dt> <dd><p>Sub-title, placed just below the <em class="math">x</em>-axis in a smaller font. </p></dd> </dl> <hr> </div> </div> <div class="section-level-extent" id="Low_002dlevel-plotting-commands"> <div class="nav-panel"> <p> Next: <a href="#Interacting-with-graphics" accesskey="n" rel="next">Interacting with graphics</a>, Previous: <a href="#High_002dlevel-plotting-commands" accesskey="p" rel="prev">High-level plotting commands</a>, Up: <a href="#Graphics" accesskey="u" rel="up">Graphical procedures</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Low_002dlevel-plotting-commands-1"><span>12.2 Low-level plotting commands<a class="copiable-link" href="#Low_002dlevel-plotting-commands-1"> ¶</a></span></h3> <p>Sometimes the high-level plotting functions don’t produce exactly the kind of plot you desire. In this case, low-level plotting commands can be used to add extra information (such as points, lines or text) to the current plot. </p> <p>Some of the more useful low-level plotting functions are: </p> <dl class="table"> <dt><a class="index-entry-id" id="index-lines"></a> <a id="index-points"></a><span><code class="code">points(x, y)</code><a class="copiable-link" href="#index-points"> ¶</a></span></dt> <dt><code class="code">lines(x, y)</code></dt> <dd><p>Adds points or connected lines to the current plot. <code class="code">plot()</code>’s <code class="code">type=</code> argument can also be passed to these functions (and defaults to <code class="code">"p"</code> for <code class="code">points()</code> and <code class="code">"l"</code> for <code class="code">lines()</code>.) </p> </dd> <dt><a id="index-text"></a><span><code class="code">text(x, y, labels, …)</code><a class="copiable-link" href="#index-text"> ¶</a></span></dt> <dd><p>Add text to a plot at points given by <code class="code">x, y</code>. Normally <code class="code">labels</code> is an integer or character vector in which case <code class="code">labels[i]</code> is plotted at point <code class="code">(x[i], y[i])</code>. The default is <code class="code">1:length(x)</code>. </p> <p><strong class="strong">Note</strong>: This function is often used in the sequence </p> <div class="example"> <pre class="example-preformatted">> plot(x, y, type="n"); text(x, y, names) </pre></div> <p>The graphics parameter <code class="code">type="n"</code> suppresses the points but sets up the axes, and the <code class="code">text()</code> function supplies special characters, as specified by the character vector <code class="code">names</code> for the points. </p> </dd> <dt><a id="index-abline"></a><span><code class="code">abline(a, b)</code><a class="copiable-link" href="#index-abline"> ¶</a></span></dt> <dt><code class="code">abline(h=<var class="var">y</var>)</code></dt> <dt><code class="code">abline(v=<var class="var">x</var>)</code></dt> <dt><code class="code">abline(<var class="var">lm.obj</var>)</code></dt> <dd><p>Adds a line of slope <code class="code">b</code> and intercept <code class="code">a</code> to the current plot. <code class="code">h=<var class="var">y</var></code> may be used to specify <em class="math">y</em>-coordinates for the heights of horizontal lines to go across a plot, and <code class="code">v=<var class="var">x</var></code> similarly for the <em class="math">x</em>-coordinates for vertical lines. Also <var class="var">lm.obj</var> may be list with a <code class="code">coefficients</code> component of length 2 (such as the result of model-fitting functions,) which are taken as an intercept and slope, in that order. </p> </dd> <dt><a id="index-polygon"></a><span><code class="code">polygon(x, y, …)</code><a class="copiable-link" href="#index-polygon"> ¶</a></span></dt> <dd><p>Draws a polygon defined by the ordered vertices in (<code class="code">x</code>, <code class="code">y</code>) and (optionally) shade it in with hatch lines, or fill it if the graphics device allows the filling of figures. </p> </dd> <dt><a id="index-legend"></a><span><code class="code">legend(x, y, legend, …)</code><a class="copiable-link" href="#index-legend"> ¶</a></span></dt> <dd><p>Adds a legend to the current plot at the specified position. Plotting characters, line styles, colors etc., are identified with the labels in the character vector <code class="code">legend</code>. At least one other argument <var class="var">v</var> (a vector the same length as <code class="code">legend</code>) with the corresponding values of the plotting unit must also be given, as follows: </p> <dl class="table"> <dt><code class="code">legend( , fill=<var class="var">v</var>)</code></dt> <dd><p>Colors for filled boxes </p></dd> <dt><code class="code">legend( , col=<var class="var">v</var>)</code></dt> <dd><p>Colors in which points or lines will be drawn </p></dd> <dt><code class="code">legend( , lty=<var class="var">v</var>)</code></dt> <dd><p>Line styles </p></dd> <dt><code class="code">legend( , lwd=<var class="var">v</var>)</code></dt> <dd><p>Line widths </p></dd> <dt><code class="code">legend( , pch=<var class="var">v</var>)</code></dt> <dd><p>Plotting characters (character vector) </p></dd> </dl> </dd> <dt><a id="index-title"></a><span><code class="code">title(main, sub)</code><a class="copiable-link" href="#index-title"> ¶</a></span></dt> <dd><p>Adds a title <code class="code">main</code> to the top of the current plot in a large font and (optionally) a sub-title <code class="code">sub</code> at the bottom in a smaller font. </p> </dd> <dt><a id="index-axis"></a><span><code class="code">axis(side, …)</code><a class="copiable-link" href="#index-axis"> ¶</a></span></dt> <dd><p>Adds an axis to the current plot on the side given by the first argument (1 to 4, counting clockwise from the bottom.) Other arguments control the positioning of the axis within or beside the plot, and tick positions and labels. Useful for adding custom axes after calling <code class="code">plot()</code> with the <code class="code">axes=FALSE</code> argument. </p></dd> </dl> <p>Low-level plotting functions usually require some positioning information (e.g., <em class="math">x</em> and <em class="math">y</em> coordinates) to determine where to place the new plot elements. Coordinates are given in terms of <em class="emph">user coordinates</em> which are defined by the previous high-level graphics command and are chosen based on the supplied data. </p> <p>Where <code class="code">x</code> and <code class="code">y</code> arguments are required, it is also sufficient to supply a single argument being a list with elements named <code class="code">x</code> and <code class="code">y</code>. Similarly a matrix with two columns is also valid input. In this way functions such as <code class="code">locator()</code> (see below) may be used to specify positions on a plot interactively. </p> <ul class="mini-toc"> <li><a href="#Mathematical-annotation" accesskey="1">Mathematical annotation</a></li> <li><a href="#Hershey-vector-fonts" accesskey="2">Hershey vector fonts</a></li> </ul> <hr> <div class="subsection-level-extent" id="Mathematical-annotation"> <div class="nav-panel"> <p> Next: <a href="#Hershey-vector-fonts" accesskey="n" rel="next">Hershey vector fonts</a>, Previous: <a href="#Low_002dlevel-plotting-commands" accesskey="p" rel="prev">Low-level plotting commands</a>, Up: <a href="#Low_002dlevel-plotting-commands" accesskey="u" rel="up">Low-level plotting commands</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Mathematical-annotation-1"><span>12.2.1 Mathematical annotation<a class="copiable-link" href="#Mathematical-annotation-1"> ¶</a></span></h4> <p>In some cases, it is useful to add mathematical symbols and formulae to a plot. This can be achieved in R by specifying an <em class="emph">expression</em> rather than a character string in any one of <code class="code">text</code>, <code class="code">mtext</code>, <code class="code">axis</code>, or <code class="code">title</code>. For example, the following code draws the formula for the Binomial probability function: </p> <div class="example"> <pre class="example-preformatted">> text(x, y, expression(paste(bgroup("(", atop(n, x), ")"), p^x, q^{n-x}))) </pre></div> <p>More information, including a full listing of the features available can obtained from within R using the commands: </p> <div class="example"> <pre class="example-preformatted">> help(plotmath) > example(plotmath) > demo(plotmath) </pre></div> <hr> </div> <div class="subsection-level-extent" id="Hershey-vector-fonts"> <div class="nav-panel"> <p> Previous: <a href="#Mathematical-annotation" accesskey="p" rel="prev">Mathematical annotation</a>, Up: <a href="#Low_002dlevel-plotting-commands" accesskey="u" rel="up">Low-level plotting commands</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Hershey-vector-fonts-1"><span>12.2.2 Hershey vector fonts<a class="copiable-link" href="#Hershey-vector-fonts-1"> ¶</a></span></h4> <p>It is possible to specify Hershey vector fonts for rendering text when using the <code class="code">text</code> and <code class="code">contour</code> functions. There are three reasons for using the Hershey fonts: </p><ul class="itemize mark-bullet"> <li>Hershey fonts can produce better output, especially on a computer screen, for rotated and/or small text. </li><li>Hershey fonts provide certain symbols that may not be available in the standard fonts. In particular, there are zodiac signs, cartographic symbols and astronomical symbols. </li><li>Hershey fonts provide Cyrillic and Japanese (Kana and Kanji) characters. </li></ul> <p>More information, including tables of Hershey characters can be obtained from within R using the commands: </p> <div class="example"> <pre class="example-preformatted">> help(Hershey) > demo(Hershey) > help(Japanese) > demo(Japanese) </pre></div> <hr> </div> </div> <div class="section-level-extent" id="Interacting-with-graphics"> <div class="nav-panel"> <p> Next: <a href="#Using-graphics-parameters" accesskey="n" rel="next">Using graphics parameters</a>, Previous: <a href="#Low_002dlevel-plotting-commands" accesskey="p" rel="prev">Low-level plotting commands</a>, Up: <a href="#Graphics" accesskey="u" rel="up">Graphical procedures</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Interacting-with-graphics-1"><span>12.3 Interacting with graphics<a class="copiable-link" href="#Interacting-with-graphics-1"> ¶</a></span></h3> <p>R also provides functions which allow users to extract or add information to a plot using a mouse. The simplest of these is the <code class="code">locator()</code> function: </p> <dl class="table"> <dt><a id="index-locator"></a><span><code class="code">locator(n, type)</code><a class="copiable-link" href="#index-locator"> ¶</a></span></dt> <dd><p>Waits for the user to select locations on the current plot using the left mouse button. This continues until <code class="code">n</code> (default 512) points have been selected, or another mouse button is pressed. The <code class="code">type</code> argument allows for plotting at the selected points and has the same effect as for high-level graphics commands; the default is no plotting. <code class="code">locator()</code> returns the locations of the points selected as a list with two components <code class="code">x</code> and <code class="code">y</code>. </p></dd> </dl> <p><code class="code">locator()</code> is usually called with no arguments. It is particularly useful for interactively selecting positions for graphic elements such as legends or labels when it is difficult to calculate in advance where the graphic should be placed. For example, to place some informative text near an outlying point, the command </p> <div class="example"> <pre class="example-preformatted">> text(locator(1), "Outlier", adj=0) </pre></div> <p>may be useful. (<code class="code">locator()</code> will be ignored if the current device, such as <code class="code">postscript</code> does not support interactive pointing.) </p> <dl class="table"> <dt><a id="index-identify"></a><span><code class="code">identify(x, y, labels)</code><a class="copiable-link" href="#index-identify"> ¶</a></span></dt> <dd><p>Allow the user to highlight any of the points defined by <code class="code">x</code> and <code class="code">y</code> (using the left mouse button) by plotting the corresponding component of <code class="code">labels</code> nearby (or the index number of the point if <code class="code">labels</code> is absent). Returns the indices of the selected points when another button is pressed. </p></dd> </dl> <p>Sometimes we want to identify particular <em class="emph">points</em> on a plot, rather than their positions. For example, we may wish the user to select some observation of interest from a graphical display and then manipulate that observation in some way. Given a number of <em class="math">(x, y)</em> coordinates in two numeric vectors <code class="code">x</code> and <code class="code">y</code>, we could use the <code class="code">identify()</code> function as follows: </p> <div class="example"> <pre class="example-preformatted">> plot(x, y) > identify(x, y) </pre></div> <p>The <code class="code">identify()</code> functions performs no plotting itself, but simply allows the user to move the mouse pointer and click the left mouse button near a point. If there is a point near the mouse pointer it will be marked with its index number (that is, its position in the <code class="code">x</code>/<code class="code">y</code> vectors) plotted nearby. Alternatively, you could use some informative string (such as a case name) as a highlight by using the <code class="code">labels</code> argument to <code class="code">identify()</code>, or disable marking altogether with the <code class="code">plot = FALSE</code> argument. When the process is terminated (see above), <code class="code">identify()</code> returns the indices of the selected points; you can use these indices to extract the selected points from the original vectors <code class="code">x</code> and <code class="code">y</code>. </p> <hr> </div> <div class="section-level-extent" id="Using-graphics-parameters"> <div class="nav-panel"> <p> Next: <a href="#Graphics-parameters" accesskey="n" rel="next">Graphics parameters list</a>, Previous: <a href="#Interacting-with-graphics" accesskey="p" rel="prev">Interacting with graphics</a>, Up: <a href="#Graphics" accesskey="u" rel="up">Graphical procedures</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Using-graphics-parameters-1"><span>12.4 Using graphics parameters<a class="copiable-link" href="#Using-graphics-parameters-1"> ¶</a></span></h3> <p>When creating graphics, particularly for presentation or publication purposes, R’s defaults do not always produce exactly that which is required. You can, however, customize almost every aspect of the display using <em class="emph">graphics parameters</em>. R maintains a list of a large number of graphics parameters which control things such as line style, colors, figure arrangement and text justification among many others. Every graphics parameter has a name (such as ‘<code class="code">col</code>’, which controls colors,) and a value (a color number, for example.) </p> <p>A separate list of graphics parameters is maintained for each active device, and each device has a default set of parameters when initialized. Graphics parameters can be set in two ways: either permanently, affecting all graphics functions which access the current device; or temporarily, affecting only a single graphics function call. </p> <ul class="mini-toc"> <li><a href="#The-par_0028_0029-function" accesskey="1">Permanent changes: The <code class="code">par()</code> function</a></li> <li><a href="#Arguments-to-graphics-functions" accesskey="2">Temporary changes: Arguments to graphics functions</a></li> </ul> <hr> <div class="subsection-level-extent" id="The-par_0028_0029-function"> <div class="nav-panel"> <p> Next: <a href="#Arguments-to-graphics-functions" accesskey="n" rel="next">Temporary changes: Arguments to graphics functions</a>, Previous: <a href="#Using-graphics-parameters" accesskey="p" rel="prev">Using graphics parameters</a>, Up: <a href="#Using-graphics-parameters" accesskey="u" rel="up">Using graphics parameters</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Permanent-changes_003a-The-par_0028_0029-function"><span>12.4.1 Permanent changes: The <code class="code">par()</code> function<a class="copiable-link" href="#Permanent-changes_003a-The-par_0028_0029-function"> ¶</a></span></h4> <a class="index-entry-id" id="index-par"></a> <a class="index-entry-id" id="index-Graphics-parameters"></a> <p>The <code class="code">par()</code> function is used to access and modify the list of graphics parameters for the current graphics device. </p> <dl class="table"> <dt><code class="code">par()</code></dt> <dd><p>Without arguments, returns a list of all graphics parameters and their values for the current device. </p></dd> <dt><code class="code">par(c("col", "lty"))</code></dt> <dd><p>With a character vector argument, returns only the named graphics parameters (again, as a list.) </p></dd> <dt><code class="code">par(col=4, lty=2)</code></dt> <dd><p>With named arguments (or a single list argument), sets the values of the named graphics parameters, and returns the original values of the parameters as a list. </p></dd> </dl> <p>Setting graphics parameters with the <code class="code">par()</code> function changes the value of the parameters <em class="emph">permanently</em>, in the sense that all future calls to graphics functions (on the current device) will be affected by the new value. You can think of setting graphics parameters in this way as setting “default” values for the parameters, which will be used by all graphics functions unless an alternative value is given. </p> <p>Note that calls to <code class="code">par()</code> <em class="emph">always</em> affect the global values of graphics parameters, even when <code class="code">par()</code> is called from within a function. This is often undesirable behavior—usually we want to set some graphics parameters, do some plotting, and then restore the original values so as not to affect the user’s R session. You can restore the initial values by saving the result of <code class="code">par()</code> when making changes, and restoring the initial values when plotting is complete. </p> <div class="example"> <pre class="example-preformatted">> oldpar <- par(col=4, lty=2) <span class="r">... plotting commands ...</span> > par(oldpar) </pre></div> <p>To save and restore <em class="emph">all</em> settable<a class="footnote" id="DOCF24" href="#FOOT24"><sup>24</sup></a> graphical parameters use </p> <div class="example"> <pre class="example-preformatted">> oldpar <- par(no.readonly=TRUE) <span class="r">... plotting commands ...</span> > par(oldpar) </pre></div> <hr> </div> <div class="subsection-level-extent" id="Arguments-to-graphics-functions"> <div class="nav-panel"> <p> Previous: <a href="#The-par_0028_0029-function" accesskey="p" rel="prev">Permanent changes: The <code class="code">par()</code> function</a>, Up: <a href="#Using-graphics-parameters" accesskey="u" rel="up">Using graphics parameters</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Temporary-changes_003a-Arguments-to-graphics-functions"><span>12.4.2 Temporary changes: Arguments to graphics functions<a class="copiable-link" href="#Temporary-changes_003a-Arguments-to-graphics-functions"> ¶</a></span></h4> <p>Graphics parameters may also be passed to (almost) any graphics function as named arguments. This has the same effect as passing the arguments to the <code class="code">par()</code> function, except that the changes only last for the duration of the function call. For example: </p> <div class="example"> <pre class="example-preformatted">> plot(x, y, pch="+") </pre></div> <p>produces a scatterplot using a plus sign as the plotting character, without changing the default plotting character for future plots. </p> <p>Unfortunately, this is not implemented entirely consistently and it is sometimes necessary to set and reset graphics parameters using <code class="code">par()</code>. </p> <hr> </div> </div> <div class="section-level-extent" id="Graphics-parameters"> <div class="nav-panel"> <p> Next: <a href="#Device-drivers" accesskey="n" rel="next">Device drivers</a>, Previous: <a href="#Using-graphics-parameters" accesskey="p" rel="prev">Using graphics parameters</a>, Up: <a href="#Graphics" accesskey="u" rel="up">Graphical procedures</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Graphics-parameters-list"><span>12.5 Graphics parameters list<a class="copiable-link" href="#Graphics-parameters-list"> ¶</a></span></h3> <p>The following sections detail many of the commonly-used graphical parameters. The R help documentation for the <code class="code">par()</code> function provides a more concise summary; this is provided as a somewhat more detailed alternative. </p> <p>Graphics parameters will be presented in the following form: </p> <dl class="table"> <dt><code class="code"><var class="var">name</var>=<var class="var">value</var></code></dt> <dd><p>A description of the parameter’s effect. <var class="var">name</var> is the name of the parameter, that is, the argument name to use in calls to <code class="code">par()</code> or a graphics function. <var class="var">value</var> is a typical value you might use when setting the parameter. </p></dd> </dl> <p>Note that <code class="code">axes</code> is <strong class="strong">not</strong> a graphics parameter but an argument to a few <code class="code">plot</code> methods: see <code class="code">xaxt</code> and <code class="code">yaxt</code>. </p> <ul class="mini-toc"> <li><a href="#Graphical-elements" accesskey="1">Graphical elements</a></li> <li><a href="#Axes-and-tick-marks" accesskey="2">Axes and tick marks</a></li> <li><a href="#Figure-margins" accesskey="3">Figure margins</a></li> <li><a href="#Multiple-figure-environment" accesskey="4">Multiple figure environment</a></li> </ul> <hr> <div class="subsection-level-extent" id="Graphical-elements"> <div class="nav-panel"> <p> Next: <a href="#Axes-and-tick-marks" accesskey="n" rel="next">Axes and tick marks</a>, Previous: <a href="#Graphics-parameters" accesskey="p" rel="prev">Graphics parameters list</a>, Up: <a href="#Graphics-parameters" accesskey="u" rel="up">Graphics parameters list</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Graphical-elements-1"><span>12.5.1 Graphical elements<a class="copiable-link" href="#Graphical-elements-1"> ¶</a></span></h4> <p>R plots are made up of points, lines, text and polygons (filled regions.) Graphical parameters exist which control how these <em class="emph">graphical elements</em> are drawn, as follows: </p> <dl class="table"> <dt><code class="code">pch="+"</code></dt> <dd><p>Character to be used for plotting points. The default varies with graphics drivers, but it is usually a circle. Plotted points tend to appear slightly above or below the appropriate position unless you use <code class="code">"."</code> as the plotting character, which produces centered points. </p> </dd> <dt><code class="code">pch=4</code></dt> <dd><p>When <code class="code">pch</code> is given as an integer between 0 and 25 inclusive, a specialized plotting symbol is produced. To see what the symbols are, use the command </p> <div class="example"> <pre class="example-preformatted">> legend(locator(1), as.character(0:25), pch = 0:25) </pre></div> <p>Those from 21 to 25 may appear to duplicate earlier symbols, but can be coloured in different ways: see the help on <code class="code">points</code> and its examples. </p> <p>In addition, <code class="code">pch</code> can be a character or a number in the range <code class="code">32:255</code> representing a character in the current font. </p> </dd> <dt><code class="code">lty=2</code></dt> <dd><p>Line types. Alternative line styles are not supported on all graphics devices (and vary on those that do) but line type 1 is always a solid line, line type 0 is always invisible, and line types 2 and onwards are dotted or dashed lines, or some combination of both. </p> </dd> <dt><code class="code">lwd=2</code></dt> <dd><p>Line widths. Desired width of lines, in multiples of the “standard” line width. Affects axis lines as well as lines drawn with <code class="code">lines()</code>, etc. Not all devices support this, and some have restrictions on the widths that can be used. </p> </dd> <dt><code class="code">col=2</code></dt> <dd><p>Colors to be used for points, lines, text, filled regions and images. A number from the current palette (see <code class="code">?palette</code>) or a named colour. </p> </dd> <dt><code class="code">col.axis</code></dt> <dt><code class="code">col.lab</code></dt> <dt><code class="code">col.main</code></dt> <dt><code class="code">col.sub</code></dt> <dd><p>The color to be used for axis annotation, <em class="math">x</em> and <em class="math">y</em> labels, main and sub-titles, respectively. </p> </dd> <dt><code class="code">font=2</code></dt> <dd><p>An integer which specifies which font to use for text. If possible, device drivers arrange so that <code class="code">1</code> corresponds to plain text, <code class="code">2</code> to bold face, <code class="code">3</code> to italic, <code class="code">4</code> to bold italic and <code class="code">5</code> to a symbol font (which include Greek letters). </p> </dd> <dt><code class="code">font.axis</code></dt> <dt><code class="code">font.lab</code></dt> <dt><code class="code">font.main</code></dt> <dt><code class="code">font.sub</code></dt> <dd><p>The font to be used for axis annotation, <em class="math">x</em> and <em class="math">y</em> labels, main and sub-titles, respectively. </p> </dd> <dt><code class="code">adj=-0.1</code></dt> <dd><p>Justification of text relative to the plotting position. <code class="code">0</code> means left justify, <code class="code">1</code> means right justify and <code class="code">0.5</code> means to center horizontally about the plotting position. The actual value is the proportion of text that appears to the left of the plotting position, so a value of <code class="code">-0.1</code> leaves a gap of 10% of the text width between the text and the plotting position. </p> </dd> <dt><code class="code">cex=1.5</code></dt> <dd><p>Character expansion. The value is the desired size of text characters (including plotting characters) relative to the default text size. </p> </dd> <dt><code class="code">cex.axis</code></dt> <dt><code class="code">cex.lab</code></dt> <dt><code class="code">cex.main</code></dt> <dt><code class="code">cex.sub</code></dt> <dd><p>The character expansion to be used for axis annotation, <em class="math">x</em> and <em class="math">y</em> labels, main and sub-titles, respectively. </p></dd> </dl> <hr> </div> <div class="subsection-level-extent" id="Axes-and-tick-marks"> <div class="nav-panel"> <p> Next: <a href="#Figure-margins" accesskey="n" rel="next">Figure margins</a>, Previous: <a href="#Graphical-elements" accesskey="p" rel="prev">Graphical elements</a>, Up: <a href="#Graphics-parameters" accesskey="u" rel="up">Graphics parameters list</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Axes-and-tick-marks-1"><span>12.5.2 Axes and tick marks<a class="copiable-link" href="#Axes-and-tick-marks-1"> ¶</a></span></h4> <p>Many of R’s high-level plots have axes, and you can construct axes yourself with the low-level <code class="code">axis()</code> graphics function. Axes have three main components: the <em class="emph">axis line</em> (line style controlled by the <code class="code">lty</code> graphics parameter), the <em class="emph">tick marks</em> (which mark off unit divisions along the axis line) and the <em class="emph">tick labels</em> (which mark the units.) These components can be customized with the following graphics parameters. </p> <dl class="table"> <dt><code class="code">lab=c(5, 7, 12)</code></dt> <dd><p>The first two numbers are the desired number of tick intervals on the <em class="math">x</em> and <em class="math">y</em> axes respectively. The third number is the desired length of axis labels, in characters (including the decimal point.) Choosing a too-small value for this parameter may result in all tick labels being rounded to the same number! </p> </dd> <dt><code class="code">las=1</code></dt> <dd><p>Orientation of axis labels. <code class="code">0</code> means always parallel to axis, <code class="code">1</code> means always horizontal, and <code class="code">2</code> means always perpendicular to the axis. </p> </dd> <dt><code class="code">mgp=c(3, 1, 0)</code></dt> <dd><p>Positions of axis components. The first component is the distance from the axis label to the axis position, in text lines. The second component is the distance to the tick labels, and the final component is the distance from the axis position to the axis line (usually zero). Positive numbers measure outside the plot region, negative numbers inside. </p> </dd> <dt><code class="code">tck=0.01</code></dt> <dd><p>Length of tick marks, as a fraction of the size of the plotting region. When <code class="code">tck</code> is small (less than 0.5) the tick marks on the <em class="math">x</em> and <em class="math">y</em> axes are forced to be the same size. A value of 1 gives grid lines. Negative values give tick marks outside the plotting region. Use <code class="code">tck=0.01</code> and <code class="code">mgp=c(1,-1.5,0)</code> for internal tick marks. </p> </dd> <dt><code class="code">xaxs="r"</code></dt> <dt><code class="code">yaxs="i"</code></dt> <dd><p>Axis styles for the <em class="math">x</em> and <em class="math">y</em> axes, respectively. With styles <code class="code">"i"</code> (internal) and <code class="code">"r"</code> (the default) tick marks always fall within the range of the data, however style <code class="code">"r"</code> leaves a small amount of space at the edges. </p> </dd> </dl> <hr> </div> <div class="subsection-level-extent" id="Figure-margins"> <div class="nav-panel"> <p> Next: <a href="#Multiple-figure-environment" accesskey="n" rel="next">Multiple figure environment</a>, Previous: <a href="#Axes-and-tick-marks" accesskey="p" rel="prev">Axes and tick marks</a>, Up: <a href="#Graphics-parameters" accesskey="u" rel="up">Graphics parameters list</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Figure-margins-1"><span>12.5.3 Figure margins<a class="copiable-link" href="#Figure-margins-1"> ¶</a></span></h4> <p>A single plot in R is known as a <code class="code">figure</code> and comprises a <em class="emph">plot region</em> surrounded by margins (possibly containing axis labels, titles, etc.) and (usually) bounded by the axes themselves. </p> <p>A typical figure is </p> <img class="image" src="images/fig11.png" alt="images/fig11"> <p>Graphics parameters controlling figure layout include: </p> <dl class="table"> <dt><code class="code">mai=c(1, 0.5, 0.5, 0)</code></dt> <dd><p>Widths of the bottom, left, top and right margins, respectively, measured in inches. </p> </dd> <dt><code class="code">mar=c(4, 2, 2, 1)</code></dt> <dd><p>Similar to <code class="code">mai</code>, except the measurement unit is text lines. </p></dd> </dl> <p><code class="code">mar</code> and <code class="code">mai</code> are equivalent in the sense that setting one changes the value of the other. The default values chosen for this parameter are often too large; the right-hand margin is rarely needed, and neither is the top margin if no title is being used. The bottom and left margins must be large enough to accommodate the axis and tick labels. Furthermore, the default is chosen without regard to the size of the device surface: for example, using the <code class="code">postscript()</code> driver with the <code class="code">height=4</code> argument will result in a plot which is about 50% margin unless <code class="code">mar</code> or <code class="code">mai</code> are set explicitly. When multiple figures are in use (see below) the margins are reduced, however this may not be enough when many figures share the same page. </p> <hr> </div> <div class="subsection-level-extent" id="Multiple-figure-environment"> <div class="nav-panel"> <p> Previous: <a href="#Figure-margins" accesskey="p" rel="prev">Figure margins</a>, Up: <a href="#Graphics-parameters" accesskey="u" rel="up">Graphics parameters list</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Multiple-figure-environment-1"><span>12.5.4 Multiple figure environment<a class="copiable-link" href="#Multiple-figure-environment-1"> ¶</a></span></h4> <p>R allows you to create an <em class="math">n</em> by <em class="math">m</em> array of figures on a single page. Each figure has its own margins, and the array of figures is optionally surrounded by an <em class="emph">outer margin</em>, as shown in the following figure. </p> <img class="image" src="images/fig12.png" alt="images/fig12"> <p>The graphical parameters relating to multiple figures are as follows: </p> <dl class="table"> <dt><code class="code">mfcol=c(3, 2)</code></dt> <dt><code class="code">mfrow=c(2, 4)</code></dt> <dd><p>Set the size of a multiple figure array. The first value is the number of rows; the second is the number of columns. The only difference between these two parameters is that setting <code class="code">mfcol</code> causes figures to be filled by column; <code class="code">mfrow</code> fills by rows. </p> <p>The layout in the Figure could have been created by setting <code class="code">mfrow=c(3,2)</code>; the figure shows the page after four plots have been drawn. </p> <p>Setting either of these can reduce the base size of symbols and text (controlled by <code class="code">par("cex")</code> and the pointsize of the device). In a layout with exactly two rows and columns the base size is reduced by a factor of 0.83: if there are three or more of either rows or columns, the reduction factor is 0.66. </p> </dd> <dt><code class="code">mfg=c(2, 2, 3, 2)</code></dt> <dd><p>Position of the current figure in a multiple figure environment. The first two numbers are the row and column of the current figure; the last two are the number of rows and columns in the multiple figure array. Set this parameter to jump between figures in the array. You can even use different values for the last two numbers than the <em class="emph">true</em> values for unequally-sized figures on the same page. </p> </dd> <dt><code class="code">fig=c(4, 9, 1, 4)/10</code></dt> <dd><p>Position of the current figure on the page. Values are the positions of the left, right, bottom and top edges respectively, as a percentage of the page measured from the bottom left corner. The example value would be for a figure in the bottom right of the page. Set this parameter for arbitrary positioning of figures within a page. If you want to add a figure to a current page, use <code class="code">new=TRUE</code> as well (unlike S). </p> </dd> <dt><code class="code">oma=c(2, 0, 3, 0)</code></dt> <dt><code class="code">omi=c(0, 0, 0.8, 0)</code></dt> <dd><p>Size of outer margins. Like <code class="code">mar</code> and <code class="code">mai</code>, the first measures in text lines and the second in inches, starting with the bottom margin and working clockwise. </p> </dd> </dl> <p>Outer margins are particularly useful for page-wise titles, etc. Text can be added to the outer margins with the <code class="code">mtext()</code> function with argument <code class="code">outer=TRUE</code>. There are no outer margins by default, however, so you must create them explicitly using <code class="code">oma</code> or <code class="code">omi</code>. </p> <p>More complicated arrangements of multiple figures can be produced by the <code class="code">split.screen()</code> and <code class="code">layout()</code> functions, as well as by the <strong class="strong">grid</strong> and <a class="url" href="https://CRAN.R-project.org/package=lattice"><strong class="strong">lattice</strong></a> packages. </p> <hr> </div> </div> <div class="section-level-extent" id="Device-drivers"> <div class="nav-panel"> <p> Next: <a href="#Dynamic-graphics" accesskey="n" rel="next">Dynamic graphics</a>, Previous: <a href="#Graphics-parameters" accesskey="p" rel="prev">Graphics parameters list</a>, Up: <a href="#Graphics" accesskey="u" rel="up">Graphical procedures</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Device-drivers-1"><span>12.6 Device drivers<a class="copiable-link" href="#Device-drivers-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Graphics-device-drivers"></a> <p>R can generate graphics (of varying levels of quality) on almost any type of display or printing device. Before this can begin, however, R needs to be informed what type of device it is dealing with. This is done by starting a <em class="emph">device driver</em>. The purpose of a device driver is to convert graphical instructions from R (“draw a line,” for example) into a form that the particular device can understand. </p> <p>Device drivers are started by calling a device driver function. There is one such function for every device driver: type <code class="code">help(Devices)</code> for a list of them all. For example, issuing the command </p> <div class="example"> <pre class="example-preformatted">> postscript() </pre></div> <p>causes all future graphics output to be sent to the printer in PostScript format. Some commonly-used device drivers are: </p> <dl class="table"> <dt><a id="index-X11"></a><span><code class="code">X11()</code><a class="copiable-link" href="#index-X11"> ¶</a></span></dt> <dd><p>For use with the X11 window system on Unix-alikes </p></dd> <dt><a id="index-windows"></a><span><code class="code">windows()</code><a class="copiable-link" href="#index-windows"> ¶</a></span></dt> <dd><p>For use on Windows </p></dd> <dt><a id="index-quartz"></a><span><code class="code">quartz()</code><a class="copiable-link" href="#index-quartz"> ¶</a></span></dt> <dd><p>For use on macOS </p></dd> <dt><a id="index-postscript"></a><span><code class="code">postscript()</code><a class="copiable-link" href="#index-postscript"> ¶</a></span></dt> <dd><p>For printing on PostScript printers, or creating PostScript graphics files. </p></dd> <dt><a id="index-pdf"></a><span><code class="code">pdf()</code><a class="copiable-link" href="#index-pdf"> ¶</a></span></dt> <dd><p>Produces a PDF file, which can also be included into PDF files. </p></dd> <dt><a id="index-png"></a><span><code class="code">png()</code><a class="copiable-link" href="#index-png"> ¶</a></span></dt> <dd><p>Produces a bitmap PNG file. (Not always available: see its help page.) </p></dd> <dt><a id="index-jpeg"></a><span><code class="code">jpeg()</code><a class="copiable-link" href="#index-jpeg"> ¶</a></span></dt> <dd><p>Produces a bitmap JPEG file, best used for <code class="code">image</code> plots. (Not always available: see its help page.) </p></dd> </dl> <p>When you have finished with a device, be sure to terminate the device driver by issuing the command </p> <div class="example"> <pre class="example-preformatted">> dev.off() </pre></div> <p>This ensures that the device finishes cleanly; for example in the case of hardcopy devices this ensures that every page is completed and has been sent to the printer. (This will happen automatically at the normal end of a session.) </p> <ul class="mini-toc"> <li><a href="#PostScript-diagrams-for-typeset-documents" accesskey="1">PostScript diagrams for typeset documents</a></li> <li><a href="#Multiple-graphics-devices" accesskey="2">Multiple graphics devices</a></li> </ul> <hr> <div class="subsection-level-extent" id="PostScript-diagrams-for-typeset-documents"> <div class="nav-panel"> <p> Next: <a href="#Multiple-graphics-devices" accesskey="n" rel="next">Multiple graphics devices</a>, Previous: <a href="#Device-drivers" accesskey="p" rel="prev">Device drivers</a>, Up: <a href="#Device-drivers" accesskey="u" rel="up">Device drivers</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="PostScript-diagrams-for-typeset-documents-1"><span>12.6.1 PostScript diagrams for typeset documents<a class="copiable-link" href="#PostScript-diagrams-for-typeset-documents-1"> ¶</a></span></h4> <p>By passing the <code class="code">file</code> argument to the <code class="code">postscript()</code> device driver function, you may store the graphics in PostScript format in a file of your choice. The plot will be in landscape orientation unless the <code class="code">horizontal=FALSE</code> argument is given, and you can control the size of the graphic with the <code class="code">width</code> and <code class="code">height</code> arguments (the plot will be scaled as appropriate to fit these dimensions.) For example, the command </p> <div class="example"> <pre class="example-preformatted">> postscript("file.ps", horizontal=FALSE, height=5, pointsize=10) </pre></div> <p>will produce a file containing PostScript code for a figure five inches high, perhaps for inclusion in a document. It is important to note that if the file named in the command already exists, it will be overwritten. This is the case even if the file was only created earlier in the same R session. </p> <p>Many usages of PostScript output will be to incorporate the figure in another document. This works best when <em class="emph">encapsulated</em> PostScript is produced: R always produces conformant output, but only marks the output as such when the <code class="code">onefile=FALSE</code> argument is supplied. This unusual notation stems from S-compatibility: it really means that the output will be a single page (which is part of the EPSF specification). Thus to produce a plot for inclusion use something like </p> <div class="example"> <pre class="example-preformatted">> postscript("plot1.eps", horizontal=FALSE, onefile=FALSE, height=8, width=6, pointsize=10) </pre></div> <hr> </div> <div class="subsection-level-extent" id="Multiple-graphics-devices"> <div class="nav-panel"> <p> Previous: <a href="#PostScript-diagrams-for-typeset-documents" accesskey="p" rel="prev">PostScript diagrams for typeset documents</a>, Up: <a href="#Device-drivers" accesskey="u" rel="up">Device drivers</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h4 class="subsection" id="Multiple-graphics-devices-1"><span>12.6.2 Multiple graphics devices<a class="copiable-link" href="#Multiple-graphics-devices-1"> ¶</a></span></h4> <p>In advanced use of R it is often useful to have several graphics devices in use at the same time. Of course only one graphics device can accept graphics commands at any one time, and this is known as the <em class="emph">current device</em>. When multiple devices are open, they form a numbered sequence with names giving the kind of device at any position. </p> <p>The main commands used for operating with multiple devices, and their meanings are as follows: </p> <dl class="table"> <dt><code class="code">X11()</code></dt> <dd><p>[UNIX] </p></dd> <dt><code class="code">windows()</code></dt> <dt><code class="code">win.printer()</code></dt> <dt><code class="code">win.metafile()</code></dt> <dd><p>[Windows] </p></dd> <dt><code class="code">quartz()</code></dt> <dd><p>[macOS] </p></dd> <dt><code class="code">postscript()</code></dt> <dt><code class="code">pdf()</code></dt> <dt><code class="code">png()</code></dt> <dt><code class="code">jpeg()</code></dt> <dt><code class="code">tiff()</code></dt> <dt><code class="code">bitmap()</code></dt> <dt><code class="code">…</code></dt> <dd><p>Each new call to a device driver function opens a new graphics device, thus extending by one the device list. This device becomes the current device, to which graphics output will be sent. </p> </dd> <dt><a id="index-dev_002elist"></a><span><code class="code">dev.list()</code><a class="copiable-link" href="#index-dev_002elist"> ¶</a></span></dt> <dd><p>Returns the number and name of all active devices. The device at position 1 on the list is always the <em class="emph">null device</em> which does not accept graphics commands at all. </p> </dd> <dt><a class="index-entry-id" id="index-dev_002eprev"></a> <a id="index-dev_002enext"></a><span><code class="code">dev.next()</code><a class="copiable-link" href="#index-dev_002enext"> ¶</a></span></dt> <dt><code class="code">dev.prev()</code></dt> <dd><p>Returns the number and name of the graphics device next to, or previous to the current device, respectively. </p> </dd> <dt><a id="index-dev_002eset"></a><span><code class="code">dev.set(which=<var class="var">k</var>)</code><a class="copiable-link" href="#index-dev_002eset"> ¶</a></span></dt> <dd><p>Can be used to change the current graphics device to the one at position <var class="var">k</var> of the device list. Returns the number and label of the device. </p> </dd> <dt><a id="index-dev_002eoff"></a><span><code class="code">dev.off(<var class="var">k</var>)</code><a class="copiable-link" href="#index-dev_002eoff"> ¶</a></span></dt> <dd><p>Terminate the graphics device at point <var class="var">k</var> of the device list. For some devices, such as <code class="code">postscript</code> devices, this will either print the file immediately or correctly complete the file for later printing, depending on how the device was initiated. </p> </dd> <dt><code class="code">dev.copy(device, …, which=<var class="var">k</var>)</code></dt> <dt><code class="code">dev.print(device, …, which=<var class="var">k</var>)</code></dt> <dd><p>Make a copy of the device <var class="var">k</var>. Here <code class="code">device</code> is a device function, such as <code class="code">postscript</code>, with extra arguments, if needed, specified by ‘<samp class="samp">…</samp>’. <code class="code">dev.print</code> is similar, but the copied device is immediately closed, so that end actions, such as printing hardcopies, are immediately performed. </p> </dd> <dt><code class="code">graphics.off()</code></dt> <dd><p>Terminate all graphics devices on the list, except the null device. </p></dd> </dl> <hr> </div> </div> <div class="section-level-extent" id="Dynamic-graphics"> <div class="nav-panel"> <p> Previous: <a href="#Device-drivers" accesskey="p" rel="prev">Device drivers</a>, Up: <a href="#Graphics" accesskey="u" rel="up">Graphical procedures</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Dynamic-graphics-1"><span>12.7 Dynamic graphics<a class="copiable-link" href="#Dynamic-graphics-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Dynamic-graphics"></a> <p>R does not have builtin capabilities for dynamic or interactive graphics, e.g. rotating point clouds or to “brushing” (interactively highlighting) points. However, extensive dynamic graphics facilities are available in the system GGobi by Swayne, Cook and Buja available from </p> <blockquote class="quotation"> <p><a class="uref" href="http://ggobi.org/">http://ggobi.org/</a> </p></blockquote> <p>and these can be accessed from R via the package <a class="url" href="https://CRAN.R-project.org/package=rggobi"><strong class="strong">rggobi</strong></a>, described at <a class="uref" href="http://ggobi.org/rggobi.html">http://ggobi.org/rggobi.html</a>. </p> <p>Also, package <a class="url" href="https://CRAN.R-project.org/package=rgl"><strong class="strong">rgl</strong></a> provides ways to interact with 3D plots, for example of surfaces. </p> <hr> </div> </div> <div class="chapter-level-extent" id="Packages"> <div class="nav-panel"> <p> Next: <a href="#OS-facilities" accesskey="n" rel="next">OS facilities</a>, Previous: <a href="#Graphics" accesskey="p" rel="prev">Graphical procedures</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="chapter" id="Packages-1"><span>13 Packages<a class="copiable-link" href="#Packages-1"> ¶</a></span></h2> <a class="index-entry-id" id="index-Packages-1"></a> <p>All R functions and datasets are stored in <em class="emph">packages</em>. Only when a package is loaded are its contents available. This is done both for efficiency (the full list would take more memory and would take longer to search than a subset), and to aid package developers, who are protected from name clashes with other code. The process of developing packages is described in <a data-manual="R-exts" href="https://cran.r-project.org/doc/manuals/R-exts.html#Creating-R-packages">Creating R packages</a> in <cite class="cite">Writing R Extensions</cite>. Here, we will describe them from a user’s point of view. </p> <p>To see which packages are installed at your site, issue the command </p> <div class="example"> <pre class="example-preformatted">> library() </pre></div> <p>with no arguments. To load a particular package (e.g., the <a class="url" href="https://CRAN.R-project.org/package=boot"><strong class="strong">boot</strong></a> package containing functions from Davison & Hinkley (1997)), use a command like </p> <div class="example"> <pre class="example-preformatted">> library(boot) </pre></div> <p>Users connected to the Internet can use the <code class="code">install.packages()</code> and <code class="code">update.packages()</code> functions (available through the <code class="code">Packages</code> menu in the Windows and macOS GUIs, see <a data-manual="R-admin" href="https://cran.r-project.org/doc/manuals/R-admin.html#Installing-packages">Installing packages</a> in <cite class="cite">R Installation and Administration</cite>) to install and update packages. </p> <p>To see which packages are currently loaded, use </p> <div class="example"> <pre class="example-preformatted">> search() </pre></div> <p>to display the search list. Some packages may be loaded but not available on the search list (see <a class="pxref" href="#Namespaces">Namespaces</a>): these will be included in the list given by </p> <div class="example"> <pre class="example-preformatted">> loadedNamespaces() </pre></div> <p>To see a list of all available help topics in an installed package, use </p> <div class="example"> <pre class="example-preformatted">> help.start() </pre></div> <p>to start the <abbr class="acronym">HTML</abbr> help system, and then navigate to the package listing in the <code class="code">Reference</code> section. </p> <ul class="mini-toc"> <li><a href="#Standard-packages" accesskey="1">Standard packages</a></li> <li><a href="#Contributed-packages-and-CRAN" accesskey="2">Contributed packages and <abbr class="acronym">CRAN</abbr></a></li> <li><a href="#Namespaces" accesskey="3">Namespaces</a></li> </ul> <hr> <div class="section-level-extent" id="Standard-packages"> <div class="nav-panel"> <p> Next: <a href="#Contributed-packages-and-CRAN" accesskey="n" rel="next">Contributed packages and <abbr class="acronym">CRAN</abbr></a>, Previous: <a href="#Packages" accesskey="p" rel="prev">Packages</a>, Up: <a href="#Packages" accesskey="u" rel="up">Packages</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Standard-packages-1"><span>13.1 Standard packages<a class="copiable-link" href="#Standard-packages-1"> ¶</a></span></h3> <p>The standard (or <em class="emph">base</em>) packages are considered part of the R source code. They contain the basic functions that allow R to work, and the datasets and standard statistical and graphical functions that are described in this manual. They should be automatically available in any R installation. For a complete list, see <a data-manual="R-FAQ" href="R-FAQ.html#Which-add_002don-packages-exist-for-R_003f">R packages</a> in <cite class="cite">R FAQ</cite>. </p> <hr> </div> <div class="section-level-extent" id="Contributed-packages-and-CRAN"> <div class="nav-panel"> <p> Next: <a href="#Namespaces" accesskey="n" rel="next">Namespaces</a>, Previous: <a href="#Standard-packages" accesskey="p" rel="prev">Standard packages</a>, Up: <a href="#Packages" accesskey="u" rel="up">Packages</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Contributed-packages-and-CRAN-1"><span>13.2 Contributed packages and <abbr class="acronym">CRAN</abbr><a class="copiable-link" href="#Contributed-packages-and-CRAN-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-CRAN"></a> <p>There are thousands of contributed packages for R, written by many different authors. Some of these packages implement specialized statistical methods, others give access to data or hardware, and others are designed to complement textbooks. Some (the <em class="emph">recommended</em> packages) are distributed with every binary distribution of R. Most are available for download from <abbr class="acronym">CRAN</abbr> (<a class="uref" href="https://CRAN.R-project.org/">https://CRAN.R-project.org/</a> and its mirrors) and other repositories such as Bioconductor (<a class="uref" href="https://www.bioconductor.org/">https://www.bioconductor.org/</a>). The <em class="emph">R FAQ</em> contains a list of CRAN packages current at the time of release, but the collection of available packages changes very frequently. </p> <hr> </div> <div class="section-level-extent" id="Namespaces"> <div class="nav-panel"> <p> Previous: <a href="#Contributed-packages-and-CRAN" accesskey="p" rel="prev">Contributed packages and <abbr class="acronym">CRAN</abbr></a>, Up: <a href="#Packages" accesskey="u" rel="up">Packages</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Namespaces-1"><span>13.3 Namespaces<a class="copiable-link" href="#Namespaces-1"> ¶</a></span></h3> <a class="index-entry-id" id="index-Namespace"></a> <a class="index-entry-id" id="index-_003a_003a"></a> <a class="index-entry-id" id="index-_003a_003a_003a"></a> <p>Packages have <em class="emph">namespaces</em>, which do three things: they allow the package writer to hide functions and data that are meant only for internal use, they prevent functions from breaking when a user (or other package writer) picks a name that clashes with one in the package, and they provide a way to refer to an object within a particular package. </p> <p>For example, <code class="code">t()</code> is the transpose function in R, but users might define their own function named <code class="code">t</code>. Namespaces prevent the user’s definition from taking precedence, and breaking every function that tries to transpose a matrix. </p> <p>There are two operators that work with namespaces. The double-colon operator <code class="code">::</code> selects definitions from a particular namespace. In the example above, the transpose function will always be available as <code class="code">base::t</code>, because it is defined in the <code class="code">base</code> package. Only functions that are exported from the package can be retrieved in this way. </p> <p>The triple-colon operator <code class="code">:::</code> may be seen in a few places in R code: it acts like the double-colon operator but also allows access to hidden objects. Users are more likely to use the <code class="code">getAnywhere()</code> function, which searches multiple packages. </p> <p>Packages are often inter-dependent, and loading one may cause others to be automatically loaded. The colon operators described above will also cause automatic loading of the associated package. When packages with namespaces are loaded automatically they are not added to the search list. </p> <hr> </div> </div> <div class="chapter-level-extent" id="OS-facilities"> <div class="nav-panel"> <p> Next: <a href="#A-sample-session" accesskey="n" rel="next">A sample session</a>, Previous: <a href="#Packages" accesskey="p" rel="prev">Packages</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="chapter" id="OS-facilities-1"><span>14 OS facilities<a class="copiable-link" href="#OS-facilities-1"> ¶</a></span></h2> <p>R has quite extensive facilities to access the OS under which it is running: this allows it to be used as a scripting language and that ability is much used by R itself, for example to install packages. </p> <p>Because R’s own scripts need to work across all platforms, considerable effort has gone into make the scripting facilities as platform-independent as is feasible. </p> <ul class="mini-toc"> <li><a href="#Files-and-directories" accesskey="1">Files and directories</a></li> <li><a href="#Filepaths" accesskey="2">Filepaths</a></li> <li><a href="#System-commands" accesskey="3">System commands</a></li> <li><a href="#Compression-and-Archives" accesskey="4">Compression and Archives</a></li> </ul> <hr> <div class="section-level-extent" id="Files-and-directories"> <div class="nav-panel"> <p> Next: <a href="#Filepaths" accesskey="n" rel="next">Filepaths</a>, Previous: <a href="#OS-facilities" accesskey="p" rel="prev">OS facilities</a>, Up: <a href="#OS-facilities" accesskey="u" rel="up">OS facilities</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Files-and-directories-1"><span>14.1 Files and directories<a class="copiable-link" href="#Files-and-directories-1"> ¶</a></span></h3> <p>There are many functions to manipulate files and directories. Here are pointers to some of the more commonly used ones. </p> <p>To create an (empty) file or directory, use <code class="code">file.create</code> or <code class="code">dir.create</code>. (These are the analogues of the POSIX utilities <code class="command">touch</code> and <code class="command">mkdir</code>.) For temporary files and directories in the R session directory see <code class="code">tempfile</code>. </p> <p>Files can be removed by either <code class="code">file.remove</code> or <code class="code">unlink</code>: the latter can remove directory trees. </p> <p>For directory listings use <code class="code">list.files</code> (also available as <code class="code">dir</code>) or <code class="code">list.dirs</code>. These can select files using a regular expression: to select by wildcards use <code class="code">Sys.glob</code>. </p> <p>Many types of information on a filepath (including for example if it is a file or directory) can be found by <code class="code">file.info</code>. </p> <p>There are several ways to find out if a file ‘exists’ (a file can exist on the filesystem and not be visible to the current user). There are functions <code class="code">file.exists</code>, <code class="code">file.access</code> and <code class="code">file_test</code> with various versions of this test: <code class="code">file_test</code> is a version of the POSIX <code class="command">test</code> command for those familiar with shell scripting. </p> <p>Function <code class="code">file.copy</code> is the R analogue of the POSIX command <code class="command">cp</code>. </p> <p>Choosing files can be done interactively by <code class="code">file.choose</code>: the Windows port has the more versatile functions <code class="code">choose.files</code> and <code class="code">choose.dir</code> and there are similar functions in the <strong class="strong">tcltk</strong> package: <code class="code">tk_choose.files</code> and <code class="code">tk_choose.dir</code>. </p> <p>Functions <code class="code">file.show</code> and <code class="code">file.edit</code> will display and edit one or more files in a way appropriate to the R port, using the facilities of a console (such as RGui on Windows or R.app on macOS) if one is in use. </p> <p>There is some support for <em class="emph">links</em> in the filesystem: see functions <code class="code">file.link</code> and <code class="code">Sys.readlink</code>. </p> <hr> </div> <div class="section-level-extent" id="Filepaths"> <div class="nav-panel"> <p> Next: <a href="#System-commands" accesskey="n" rel="next">System commands</a>, Previous: <a href="#Files-and-directories" accesskey="p" rel="prev">Files and directories</a>, Up: <a href="#OS-facilities" accesskey="u" rel="up">OS facilities</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Filepaths-1"><span>14.2 Filepaths<a class="copiable-link" href="#Filepaths-1"> ¶</a></span></h3> <p>With a few exceptions, R relies on the underlying OS functions to manipulate filepaths. Some aspects of this are allowed to depend on the OS, and do, even down to the version of the OS. There are POSIX standards for how OSes should interpret filepaths and many R users assume POSIX compliance: but Windows does not claim to be compliant and other OSes may be less than completely compliant. </p> <p>The following are some issues which have been encountered with filepaths. </p> <ul class="itemize mark-bullet"> <li>POSIX filesystems are case-sensitive, so <samp class="file">foo.png</samp> and <samp class="file">Foo.PNG</samp> are different files. However, the defaults on Windows and macOS are to be case-insensitive, and FAT filesystems (commonly used on removable storage) are not normally case-sensitive (and all filepaths may be mapped to lower case). </li><li>Almost all the Windows’ OS services support the use of slash or backslash as the filepath separator, and R converts the known exceptions to the form required by Windows. </li><li>The behaviour of filepaths with a trailing slash is OS-dependent. Such paths are not valid on Windows and should not be expected to work. POSIX-2008 requires such paths to match only directories, but earlier versions allowed them to also match files. So they are best avoided. </li><li>Multiple slashes in filepaths such as <samp class="file">/abc//def</samp> are valid on POSIX filesystems and treated as if there was only one slash. They are <em class="emph">usually</em> accepted by Windows’ OS functions. However, leading double slashes may have a different meaning. </li><li>Windows’ UNC filepaths (such as <samp class="file">\\server\dir1\dir2\file</samp> and <samp class="file">\\?\UNC\server\dir1\dir2\file</samp>) are not supported, but they may work in some R functions. POSIX filesystems are allowed to treat a leading double slash specially. </li><li>Windows allows filepaths containing drives and relative to the current directory on a drive, e.g. <samp class="file">d:foo/bar</samp> refers to <samp class="file">d:/a/b/c/foo/bar</samp> if the current directory <em class="emph">on drive <samp class="file">d:</samp></em> is <samp class="file">/a/b/c</samp>. It is intended that these work, but the use of absolute paths is safer. </li></ul> <p>Functions <code class="code">basename</code> and <code class="code">dirname</code> select parts of a file path: the recommended way to assemble a file path from components is <code class="code">file.path</code>. Function <code class="code">pathexpand</code> does ‘tilde expansion’, substituting values for home directories (the current user’s, and perhaps those of other users). </p> <p>On filesystems with links, a single file can be referred to by many filepaths. Function <code class="code">normalizePath</code> will find a canonical filepath. </p> <p>Windows has the concepts of short (‘8.3’) and long file names: <code class="code">normalizePath</code> will return an absolute path using long file names and <code class="code">shortPathName</code> will return a version using short names. The latter does not contain spaces and uses backslash as the separator, so is sometimes useful for exporting names from R. </p> <p>File <em class="emph">permissions</em> are a related topic. R has support for the POSIX concepts of read/write/execute permission for owner/group/all but this may be only partially supported on the filesystem, so for example on Windows only read-only files (for the account running the R session) are recognized. Access Control Lists (<abbr class="abbr">ACL</abbr>s) are employed on several filesystems, but do not have an agreed standard and R has no facilities to control them. Use <code class="code">Sys.chmod</code> to change permissions. </p> <hr> </div> <div class="section-level-extent" id="System-commands"> <div class="nav-panel"> <p> Next: <a href="#Compression-and-Archives" accesskey="n" rel="next">Compression and Archives</a>, Previous: <a href="#Filepaths" accesskey="p" rel="prev">Filepaths</a>, Up: <a href="#OS-facilities" accesskey="u" rel="up">OS facilities</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="System-commands-1"><span>14.3 System commands<a class="copiable-link" href="#System-commands-1"> ¶</a></span></h3> <p>Functions <code class="code">system</code> and <code class="code">system2</code> are used to invoke a system command and optionally collect its output. <code class="code">system2</code> is a little more general but its main advantage is that it is easier to write cross-platform code using it. </p> <p><code class="code">system</code> behaves differently on Windows from other OSes (because the API C call of that name does). Elsewhere it invokes a shell to run the command: the Windows port of R has a function <code class="code">shell</code> to do that. </p> <p>To find out if the OS includes a command, use <code class="code">Sys.which</code>, which attempts to do this in a cross-platform way (unfortunately it is not a standard OS service). </p> <p>Function <code class="code">shQuote</code> will quote filepaths as needed for commands in the current OS. </p> <hr> </div> <div class="section-level-extent" id="Compression-and-Archives"> <div class="nav-panel"> <p> Previous: <a href="#System-commands" accesskey="p" rel="prev">System commands</a>, Up: <a href="#OS-facilities" accesskey="u" rel="up">OS facilities</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="section" id="Compression-and-Archives-1"><span>14.4 Compression and Archives<a class="copiable-link" href="#Compression-and-Archives-1"> ¶</a></span></h3> <p>Recent versions of R have extensive facilities to read and write compressed files, often transparently. Reading of files in R is to a very large extent done by <em class="emph">connections</em>, and the <code class="code">file</code> function which is used to open a connection to a file (or a URL) and is able to identify the compression used from the ‘magic’ header of the file. </p> <p>The type of compression which has been supported for longest is <code class="command">gzip</code> compression, and that remains a good general compromise. Files compressed by the earlier Unix <code class="command">compress</code> utility can also be read, but these are becoming rare. Two other forms of compression, those of the <code class="command">bzip2</code> and <code class="command">xz</code> utilities are also available. These generally achieve higher rates of compression (depending on the file, much higher) at the expense of slower decompression and much slower compression. </p> <p>There is some confusion between <code class="command">xz</code> and <code class="command">lzma</code> compression (see <a class="uref" href="https://en.wikipedia.org/wiki/Xz">https://en.wikipedia.org/wiki/Xz</a> and <a class="uref" href="https://en.wikipedia.org/wiki/LZMA">https://en.wikipedia.org/wiki/LZMA</a>): R can read files compressed by most versions of either. </p> <p>File archives are single files which contain a collection of files, the most common ones being ‘tarballs’ and zip files as used to distribute R packages. R can list and unpack both (see functions <code class="code">untar</code> and <code class="code">unzip</code>) and create both (for <code class="command">zip</code> with the help of an external program). </p> <hr> </div> </div> <div class="appendix-level-extent" id="A-sample-session"> <div class="nav-panel"> <p> Next: <a href="#Invoking-R" accesskey="n" rel="next">Invoking R</a>, Previous: <a href="#OS-facilities" accesskey="p" rel="prev">OS facilities</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="appendix" id="A-sample-session-1"><span>Appendix A A sample session<a class="copiable-link" href="#A-sample-session-1"> ¶</a></span></h2> <p>The following session is intended to introduce to you some features of the R environment by using them. Many features of the system will be unfamiliar and puzzling at first, but this puzzlement will soon disappear. </p> <p>Start R appropriately for your platform (see <a class="pxref" href="#Invoking-R">Invoking R</a>). </p> <p>The R program begins, with a banner. </p> <p>(Within R code, the prompt on the left hand side will not be shown to avoid confusion.) </p> <dl class="table"> <dt><code class="code">help.start()</code></dt> <dd><p>Start the <abbr class="acronym">HTML</abbr> interface to on-line help (using a web browser available at your machine). You should briefly explore the features of this facility with the mouse. </p> <p>Iconify the help window and move on to the next part. </p> </dd> <dt><code class="code">x <- rnorm(50)</code></dt> <dt><code class="code">y <- rnorm(x)</code></dt> <dd><p>Generate two pseudo-random normal vectors of <em class="math">x</em>- and <em class="math">y</em>-coordinates. </p> </dd> <dt><code class="code">plot(x, y)</code></dt> <dd><p>Plot the points in the plane. A graphics window will appear automatically. </p> </dd> <dt><code class="code">ls()</code></dt> <dd><p>See which R objects are now in the R workspace. </p> </dd> <dt><code class="code">rm(x, y)</code></dt> <dd><p>Remove objects no longer needed. (Clean up). </p> </dd> <dt><code class="code">x <- 1:20</code></dt> <dd><p>Make <em class="math">x = (1, 2, ..., 20)</em>. </p> </dd> <dt><code class="code">w <- 1 + sqrt(x)/2</code></dt> <dd><p>A ‘weight’ vector of standard deviations. </p> </dd> <dt><code class="code">dummy <- data.frame(x=x, y= x + rnorm(x)*w)</code></dt> <dt><code class="code">dummy</code></dt> <dd><p>Make a <em class="emph">data frame</em> of two columns, <em class="math">x</em> and <em class="math">y</em>, and look at it. </p> </dd> <dt><code class="code">fm <- lm(y ~ x, data=dummy)</code></dt> <dt><code class="code">summary(fm)</code></dt> <dd><p>Fit a simple linear regression and look at the analysis. With <code class="code">y</code> to the left of the tilde, we are modelling <em class="math">y</em> dependent on <em class="math">x</em>. </p> </dd> <dt><code class="code">fm1 <- lm(y ~ x, data=dummy, weight=1/w^2)</code></dt> <dt><code class="code">summary(fm1)</code></dt> <dd><p>Since we know the standard deviations, we can do a weighted regression. </p> </dd> <dt><code class="code">attach(dummy)</code></dt> <dd><p>Make the columns in the data frame visible as variables. </p> </dd> <dt><code class="code">lrf <- lowess(x, y)</code></dt> <dd><p>Make a nonparametric local regression function. </p> </dd> <dt><code class="code">plot(x, y)</code></dt> <dd><p>Standard point plot. </p> </dd> <dt><code class="code">lines(x, lrf$y)</code></dt> <dd><p>Add in the local regression. </p> </dd> <dt><code class="code">abline(0, 1, lty=3)</code></dt> <dd><p>The true regression line: (intercept 0, slope 1). </p> </dd> <dt><code class="code">abline(coef(fm))</code></dt> <dd><p>Unweighted regression line. </p> </dd> <dt><code class="code">abline(coef(fm1), col = "red")</code></dt> <dd><p>Weighted regression line. </p> </dd> <dt><code class="code">detach()</code></dt> <dd><p>Remove data frame from the search path. </p> </dd> <dt><code class="code">plot(fitted(fm), resid(fm),</code></dt> <dt><code class="code"> xlab="Fitted values"<!-- /@w -->,</code></dt> <dt><code class="code"> ylab="Residuals"<!-- /@w -->,</code></dt> <dt><code class="code"> main="Residuals vs Fitted")<!-- /@w --></code></dt> <dd><p>A standard regression diagnostic plot to check for heteroscedasticity. Can you see it? </p> </dd> <dt><code class="code">qqnorm(resid(fm), main="Residuals Rankit Plot")</code></dt> <dd><p>A normal scores plot to check for skewness, kurtosis and outliers. (Not very useful here.) </p> </dd> <dt><code class="code">rm(fm, fm1, lrf, x, dummy)</code></dt> <dd><p>Clean up again. </p></dd> </dl> <p>The next section will look at data from the classical experiment of Michelson to measure the speed of light. This dataset is available in the <code class="code">morley</code> object, but we will read it to illustrate the <code class="code">read.table</code> function. </p> <dl class="table"> <dt><code class="code">filepath <- system.file("data", "morley.tab" , package="datasets")</code></dt> <dt><code class="code">filepath</code></dt> <dd><p>Get the path to the data file. </p> </dd> <dt><code class="code">file.show(filepath)</code></dt> <dd><p>Optional. Look at the file. </p> </dd> <dt><code class="code">mm <- read.table(filepath)</code></dt> <dt><code class="code">mm</code></dt> <dd><p>Read in the Michelson data as a data frame, and look at it. There are five experiments (column <code class="code">Expt</code>) and each has 20 runs (column <code class="code">Run</code>) and <code class="code">sl</code> is the recorded speed of light, suitably coded. </p> </dd> <dt><code class="code">mm$Expt <- factor(mm$Expt)</code></dt> <dt><code class="code">mm$Run <- factor(mm$Run)</code></dt> <dd><p>Change <code class="code">Expt</code> and <code class="code">Run</code> into factors. </p> </dd> <dt><code class="code">attach(mm)</code></dt> <dd><p>Make the data frame visible at position 2 (the default). </p> </dd> <dt><code class="code">plot(Expt, Speed, main="Speed of Light Data", xlab="Experiment No.")</code></dt> <dd><p>Compare the five experiments with simple boxplots. </p> </dd> <dt><code class="code">fm <- aov(Speed ~ Run + Expt, data=mm)</code></dt> <dt><code class="code">summary(fm)</code></dt> <dd><p>Analyze as a randomized block, with ‘runs’ and ‘experiments’ as factors. </p> </dd> <dt><code class="code">fm0 <- update(fm, . ~ . - Run)</code></dt> <dt><code class="code">anova(fm0, fm)</code></dt> <dd><p>Fit the sub-model omitting ‘runs’, and compare using a formal analysis of variance. </p> </dd> <dt><code class="code">detach()</code></dt> <dt><code class="code">rm(fm, fm0)</code></dt> <dd><p>Clean up before moving on. </p> </dd> </dl> <p>We now look at some more graphical features: contour and image plots. </p> <dl class="table"> <dt><code class="code">x <- seq(-pi, pi, len=50)</code></dt> <dt><code class="code">y <- x</code></dt> <dd><p><em class="math">x</em> is a vector of 50 equally spaced values in the interval [-pi\, pi]. <em class="math">y</em> is the same. </p> </dd> <dt><code class="code">f <- outer(x, y, function(x, y) cos(y)/(1 + x^2))</code></dt> <dd><p><em class="math">f</em> is a square matrix, with rows and columns indexed by <em class="math">x</em> and <em class="math">y</em> respectively, of values of the function cos(y)/(1 + x^2). </p> </dd> <dt><code class="code">oldpar <- par(no.readonly = TRUE)</code></dt> <dt><code class="code">par(pty="s")</code></dt> <dd><p>Save the plotting parameters and set the plotting region to “square”. </p> </dd> <dt><code class="code">contour(x, y, f)</code></dt> <dt><code class="code">contour(x, y, f, nlevels=15, add=TRUE)</code></dt> <dd><p>Make a contour map of <em class="math">f</em>; add in more lines for more detail. </p> </dd> <dt><code class="code">fa <- (f-t(f))/2</code></dt> <dd><p><code class="code">fa</code> is the “asymmetric part” of <em class="math">f</em>. (<code class="code">t()</code> is transpose). </p> </dd> <dt><code class="code">contour(x, y, fa, nlevels=15)</code></dt> <dd><p>Make a contour plot, … </p> </dd> <dt><code class="code">par(oldpar)</code></dt> <dd><p>… and restore the old graphics parameters. </p> </dd> <dt><code class="code">image(x, y, f)</code></dt> <dt><code class="code">image(x, y, fa)</code></dt> <dd><p>Make some high density image plots, (of which you can get hardcopies if you wish), … </p> </dd> <dt><code class="code">objects(); rm(x, y, f, fa)</code></dt> <dd><p>… and clean up before moving on. </p></dd> </dl> <p>R can do complex arithmetic, also. </p> <dl class="table"> <dt><code class="code">th <- seq(-pi, pi, len=100)</code></dt> <dt><code class="code">z <- exp(1i*th)</code></dt> <dd><p><code class="code">1i</code> is used for the complex number <em class="math">i</em>. </p> </dd> <dt><code class="code">par(pty="s")</code></dt> <dt><code class="code">plot(z, type="l")</code></dt> <dd><p>Plotting complex arguments means plot imaginary versus real parts. This should be a circle. </p> </dd> <dt><code class="code">w <- rnorm(100) + rnorm(100)*1i</code></dt> <dd><p>Suppose we want to sample points within the unit circle. One method would be to take complex numbers with standard normal real and imaginary parts … </p> </dd> <dt><code class="code">w <- ifelse(Mod(w) > 1, 1/w, w)</code></dt> <dd><p>… and to map any outside the circle onto their reciprocal. </p> </dd> <dt><code class="code">plot(w, xlim=c(-1,1), ylim=c(-1,1), pch="+",xlab="x", ylab="y")</code></dt> <dt><code class="code">lines(z)</code></dt> <dd><p>All points are inside the unit circle, but the distribution is not uniform. </p> </dd> <dt><code class="code">w <- sqrt(runif(100))*exp(2*pi*runif(100)*1i)</code></dt> <dt><code class="code">plot(w, xlim=c(-1,1), ylim=c(-1,1), pch="+", xlab="x", ylab="y")</code></dt> <dt><code class="code">lines(z)</code></dt> <dd><p>The second method uses the uniform distribution. The points should now look more evenly spaced over the disc. </p> </dd> <dt><code class="code">rm(th, w, z)</code></dt> <dd><p>Clean up again. </p> </dd> <dt><code class="code">q()</code></dt> <dd><p>Quit the R program. You will be asked if you want to save the R workspace, and for an exploratory session like this, you probably do not want to save it. </p></dd> </dl> <hr> </div> <div class="appendix-level-extent" id="Invoking-R"> <div class="nav-panel"> <p> Next: <a href="#The-command_002dline-editor" accesskey="n" rel="next">The command-line editor</a>, Previous: <a href="#A-sample-session" accesskey="p" rel="prev">A sample session</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="appendix" id="Invoking-R-1"><span>Appendix B Invoking R<a class="copiable-link" href="#Invoking-R-1"> ¶</a></span></h2> <p>Users of R on Windows or macOS should read the OS-specific section first, but command-line use is also supported. </p> <ul class="mini-toc"> <li><a href="#Invoking-R-from-the-command-line" accesskey="1">Invoking R from the command line</a></li> <li><a href="#Invoking-R-under-Windows" accesskey="2">Invoking R under Windows</a></li> <li><a href="#Invoking-R-under-macOS" accesskey="3">Invoking R under macOS</a></li> <li><a href="#Scripting-with-R" accesskey="4">Scripting with R</a></li> </ul> <hr> <div class="appendixsec-level-extent" id="Invoking-R-from-the-command-line"> <div class="nav-panel"> <p> Next: <a href="#Invoking-R-under-Windows" accesskey="n" rel="next">Invoking R under Windows</a>, Previous: <a href="#Invoking-R" accesskey="p" rel="prev">Invoking R</a>, Up: <a href="#Invoking-R" accesskey="u" rel="up">Invoking R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="appendixsec" id="Invoking-R-from-the-command-line-1"><span>B.1 Invoking R from the command line<a class="copiable-link" href="#Invoking-R-from-the-command-line-1"> ¶</a></span></h3> <p>When working at a command line on UNIX or Windows, the command ‘<samp class="samp">R</samp>’ can be used both for starting the main R program in the form </p> <div class="display"> <pre class="display-preformatted"><code class="code">R</code> [<var class="var">options</var>] [<code class="code"><</code><var class="var">infile</var>] [<code class="code">></code><var class="var">outfile</var>], </pre></div> <p>or, via the <code class="code">R CMD</code> interface, as a wrapper to various R tools (e.g., for processing files in R documentation format or manipulating add-on packages) which are not intended to be called “directly”. </p> <p>At the Windows command-line, <code class="command">Rterm.exe</code> is preferred to <code class="command">R</code>. </p> <p>You need to ensure that either the environment variable <code class="env">TMPDIR</code> is unset or it points to a valid place to create temporary files and directories. </p> <p>Most options control what happens at the beginning and at the end of an R session. The startup mechanism is as follows (see also the on-line help for topic ‘<samp class="samp">Startup</samp>’ for more information, and the section below for some Windows-specific details). </p> <ul class="itemize mark-bullet"> <li>Unless <samp class="option">--no-environ</samp> was given, R searches for user and site files to process for setting environment variables. The name of the site file is the one pointed to by the environment variable <code class="env">R_ENVIRON</code>; if this is unset, <samp class="file"><var class="var">R_HOME</var>/etc/Renviron.site</samp> is used (if it exists). The user file is the one pointed to by the environment variable <code class="env">R_ENVIRON_USER</code> if this is set; otherwise, files <samp class="file">.Renviron</samp> in the current or in the user’s home directory (in that order) are searched for. These files should contain lines of the form ‘<samp class="samp"><var class="var">name</var>=<var class="var">value</var></samp>’. (See <code class="code">help("Startup")</code> for a precise description.) Variables you might want to set include <code class="env">R_PAPERSIZE</code> (the default paper size), <code class="env">R_PRINTCMD</code> (the default print command) and <code class="env">R_LIBS</code> (specifies the list of R library trees searched for add-on packages). </li><li>Then R searches for the site-wide startup profile unless the command line option <samp class="option">--no-site-file</samp> was given. The name of this file is taken from the value of the <code class="env">R_PROFILE</code> environment variable. If that variable is unset, the default <samp class="file"><var class="var">R_HOME</var>/etc/Rprofile.site</samp> is used if this exists. </li><li>Then, unless <samp class="option">--no-init-file</samp> was given, R searches for a user profile and sources it. The name of this file is taken from the environment variable <code class="env">R_PROFILE_USER</code>; if unset, a file called <samp class="file">.Rprofile</samp> in the current directory or in the user’s home directory (in that order) is searched for. </li><li>It also loads a saved workspace from file <samp class="file">.RData</samp> in the current directory if there is one (unless <samp class="option">--no-restore</samp> or <samp class="option">--no-restore-data</samp> was specified). </li><li>Finally, if a function <code class="code">.First()</code> exists, it is executed. This function (as well as <code class="code">.Last()</code> which is executed at the end of the R session) can be defined in the appropriate startup profiles, or reside in <samp class="file">.RData</samp>. </li></ul> <p>In addition, there are options for controlling the memory available to the R process (see the on-line help for topic ‘<samp class="samp">Memory</samp>’ for more information). Users will not normally need to use these unless they are trying to limit the amount of memory used by R. </p> <p>R accepts the following command-line options. </p> <dl class="table"> <dt><samp class="option">--help</samp></dt> <dt><samp class="option">-h</samp></dt> <dd><p>Print short help message to standard output and exit successfully. </p> </dd> <dt><samp class="option">--version</samp></dt> <dd><p>Print version information to standard output and exit successfully. </p> </dd> <dt><samp class="option">--encoding=<var class="var">enc</var></samp></dt> <dd><p>Specify the encoding to be assumed for input from the console or <code class="code">stdin</code>. This needs to be an encoding known to <code class="code">iconv</code>: see its help page. (<code class="code">--encoding <var class="var">enc</var></code> is also accepted.) The input is re-encoded to the locale R is running in and needs to be representable in the latter’s encoding (so e.g. you cannot re-encode Greek text in a French locale unless that locale uses the UTF-8 encoding). </p> </dd> <dt><samp class="option">RHOME</samp></dt> <dd><p>Print the path to the R “home directory” to standard output and exit successfully. Apart from the front-end shell script and the man page, R installation puts everything (executables, packages, etc.) into this directory. </p> </dd> <dt><samp class="option">--save</samp></dt> <dt><samp class="option">--no-save</samp></dt> <dd><p>Control whether data sets should be saved or not at the end of the R session. If neither is given in an interactive session, the user is asked for the desired behavior when ending the session with <kbd class="kbd">q()</kbd>; in non-interactive use one of these must be specified or implied by some other option (see below). </p> </dd> <dt><samp class="option">--no-environ</samp></dt> <dd><p>Do not read any user file to set environment variables. </p> </dd> <dt><samp class="option">--no-site-file</samp></dt> <dd><p>Do not read the site-wide profile at startup. </p> </dd> <dt><samp class="option">--no-init-file</samp></dt> <dd><p>Do not read the user’s profile at startup. </p> </dd> <dt><samp class="option">--restore</samp></dt> <dt><samp class="option">--no-restore</samp></dt> <dt><samp class="option">--no-restore-data</samp></dt> <dd><p>Control whether saved images (file <samp class="file">.RData</samp> in the directory where R was started) should be restored at startup or not. The default is to restore. (<samp class="option">--no-restore</samp> implies all the specific <samp class="option">--no-restore-*</samp> options.) </p> </dd> <dt><samp class="option">--no-restore-history</samp></dt> <dd><p>Control whether the history file (normally file <samp class="file">.Rhistory</samp> in the directory where R was started, but can be set by the environment variable <code class="env">R_HISTFILE</code>) should be restored at startup or not. The default is to restore. </p> </dd> <dt><samp class="option">--no-Rconsole</samp></dt> <dd><p>(Windows only) Prevent loading the <samp class="file">Rconsole</samp> file at startup. </p> </dd> <dt><samp class="option">--vanilla</samp></dt> <dd><p>Combine <samp class="option">--no-save</samp>, <samp class="option">--no-environ</samp>, <samp class="option">--no-site-file</samp>, <samp class="option">--no-init-file</samp> and <samp class="option">--no-restore</samp>. Under Windows, this also includes <samp class="option">--no-Rconsole</samp>. </p> </dd> <dt><samp class="option">-f <var class="var">file</var></samp></dt> <dt><samp class="option">--file=<var class="var">file</var></samp></dt> <dd><p>(not <code class="command">Rgui.exe</code>) Take input from <var class="var">file</var>: ‘<samp class="samp">-</samp>’ means <code class="code">stdin</code>. Implies <samp class="option">--no-save</samp> unless <samp class="option">--save</samp> has been set. On a Unix-alike, shell metacharacters should be avoided in <var class="var">file</var> (but spaces are allowed). </p> </dd> <dt><samp class="option">-e <var class="var">expression</var></samp></dt> <dd><p>(not <code class="command">Rgui.exe</code>) Use <var class="var">expression</var> as an input line. One or more <samp class="option">-e</samp> options can be used, but not together with <samp class="option">-f</samp> or <samp class="option">--file</samp>. Implies <samp class="option">--no-save</samp> unless <samp class="option">--save</samp> has been set. (There is a limit of 10,000 bytes on the total length of expressions used in this way. Expressions containing spaces or shell metacharacters will need to be quoted.) </p> </dd> <dt><samp class="option">--no-readline</samp></dt> <dd><p>(UNIX only) Turn off command-line editing via <strong class="strong">readline</strong>. This is useful when running R from within Emacs using the <abbr class="acronym">ESS</abbr> (“Emacs Speaks Statistics”) package. See <a class="xref" href="#The-command_002dline-editor">The command-line editor</a>, for more information. Command-line editing is enabled for default interactive use (see <samp class="option">--interactive</samp>). This option also affects tilde-expansion: see the help for <code class="code">path.expand</code>. </p> </dd> <dt><samp class="option">--min-vsize=<var class="var">N</var></samp></dt> <dt><samp class="option">--min-nsize=<var class="var">N</var></samp></dt> <dd><p>For expert use only: set the initial trigger sizes for garbage collection of vector heap (in bytes) and <em class="emph">cons cells</em> (number) respectively. Suffix ‘<samp class="samp">M</samp>’ specifies megabytes or millions of cells respectively. The defaults are 6Mb and 350k respectively and can also be set by environment variables <code class="env">R_NSIZE</code> and <code class="env">R_VSIZE</code>. </p> </dd> <dt><samp class="option">--max-ppsize=<var class="var">N</var></samp></dt> <dd><p>Specify the maximum size of the pointer protection stack as <var class="var">N</var> locations. This defaults to 10000, but can be increased to allow large and complicated calculations to be done. Currently the maximum value accepted is 100000. </p> </dd> <dt><samp class="option">--quiet</samp></dt> <dt><samp class="option">--silent</samp></dt> <dt><samp class="option">-q</samp></dt> <dd><p>Do not print out the initial copyright and welcome messages. </p> </dd> <dt><samp class="option">--no-echo</samp></dt> <dd><p>Make R run as quietly as possible. This option is intended to support programs which use R to compute results for them. It implies <samp class="option">--quiet</samp> and <samp class="option">--no-save</samp>. </p> </dd> <dt><samp class="option">--interactive</samp></dt> <dd><p>(UNIX only) Assert that R really is being run interactively even if input has been redirected: use if input is from a FIFO or pipe and fed from an interactive program. (The default is to deduce that R is being run interactively if and only if <samp class="file">stdin</samp> is connected to a terminal or <code class="code">pty</code>.) Using <samp class="option">-e</samp>, <samp class="option">-f</samp> or <samp class="option">--file</samp> asserts non-interactive use even if <samp class="option">--interactive</samp> is given. </p> <p>Note that this does not turn on command-line editing. </p> </dd> <dt><samp class="option">--ess</samp></dt> <dd><p>(Windows only) Set <code class="code">Rterm</code> up for use by <code class="code">R-inferior-mode</code> in <abbr class="acronym">ESS</abbr>, including asserting interactive use (without the command-line editor) and no buffering of <samp class="file">stdout</samp>. </p> </dd> <dt><samp class="option">--verbose</samp></dt> <dd><p>Print more information about progress, and in particular set R’s option <code class="code">verbose</code> to <code class="code">TRUE</code>. R code uses this option to control the printing of diagnostic messages. </p> </dd> <dt><samp class="option">--debugger=<var class="var">name</var></samp></dt> <dt><samp class="option">-d <var class="var">name</var></samp></dt> <dd><p>(UNIX only) Run R through debugger <var class="var">name</var>. For most debuggers (the exceptions are <code class="command">valgrind</code> and recent versions of <code class="command">gdb</code>), further command line options are disregarded, and should instead be given when starting the R executable from inside the debugger. </p> </dd> <dt><samp class="option">--gui=<var class="var">type</var></samp></dt> <dt><samp class="option">-g <var class="var">type</var></samp></dt> <dd><p>(UNIX only) Use <var class="var">type</var> as graphical user interface (note that this also includes interactive graphics). Currently, possible values for <var class="var">type</var> are ‘<samp class="samp">X11</samp>’ (the default) and, provided that ‘<samp class="samp">Tcl/Tk</samp>’ support is available, ‘<samp class="samp">Tk</samp>’. (For back-compatibility, ‘<samp class="samp">x11</samp>’ and ‘<samp class="samp">tk</samp>’ are accepted.) </p> </dd> <dt><samp class="option">--arch=<var class="var">name</var></samp></dt> <dd><p>(UNIX only) Run the specified sub-architecture. </p> </dd> <dt><samp class="option">--args</samp></dt> <dd><p>This flag does nothing except cause the rest of the command line to be skipped: this can be useful to retrieve values from it with <code class="code">commandArgs(TRUE)</code>. </p></dd> </dl> <p>Note that input and output can be redirected in the usual way (using ‘<samp class="samp"><</samp>’ and ‘<samp class="samp">></samp>’), but the line length limit of 4095 bytes still applies. Warning and error messages are sent to the error channel (<code class="code">stderr</code>). </p> <p>The command <code class="code">R CMD</code> allows the invocation of various tools which are useful in conjunction with R, but not intended to be called “directly”. The general form is </p> <div class="example"> <pre class="example-preformatted">R CMD <var class="var">command</var> <var class="var">args</var> </pre></div> <p>where <var class="var">command</var> is the name of the tool and <var class="var">args</var> the arguments passed on to it. </p> <p>Currently, the following tools are available. </p> <dl class="table"> <dt><code class="code">BATCH</code></dt> <dd><p>Run R in batch mode. Runs <code class="command">R --restore --save</code> with possibly further options (see <code class="code">?BATCH</code>). </p></dd> <dt><code class="code">COMPILE</code></dt> <dd><p>(UNIX only) Compile C, C++, Fortran … files for use with R. </p></dd> <dt><code class="code">SHLIB</code></dt> <dd><p>Build shared library for dynamic loading. </p></dd> <dt><code class="code">INSTALL</code></dt> <dd><p>Install add-on packages. </p></dd> <dt><code class="code">REMOVE</code></dt> <dd><p>Remove add-on packages. </p></dd> <dt><code class="code">build</code></dt> <dd><p>Build (that is, package) add-on packages. </p></dd> <dt><code class="code">check</code></dt> <dd><p>Check add-on packages. </p></dd> <dt><code class="code">LINK</code></dt> <dd><p>(UNIX only) Front-end for creating executable programs. </p></dd> <dt><code class="code">Rprof</code></dt> <dd><p>Post-process R profiling files. </p></dd> <dt><code class="code">Rdconv</code></dt> <dt><code class="code">Rd2txt</code></dt> <dd><p>Convert Rd format to various other formats, including <abbr class="acronym">HTML</abbr>, LaTeX, plain text, and extracting the examples. <code class="code">Rd2txt</code> can be used as shorthand for <code class="code">Rd2conv -t txt</code>. </p></dd> <dt><code class="code">Rd2pdf</code></dt> <dd><p>Convert Rd format to PDF. </p></dd> <dt><code class="code">Stangle</code></dt> <dd><p>Extract S/R code from Sweave or other vignette documentation </p></dd> <dt><code class="code">Sweave</code></dt> <dd><p>Process Sweave or other vignette documentation </p></dd> <dt><code class="code">Rdiff</code></dt> <dd><p>Diff R output ignoring headers etc </p></dd> <dt><code class="code">config</code></dt> <dd><p>Obtain configuration information </p></dd> <dt><code class="code">javareconf</code></dt> <dd><p>(Unix only) Update the Java configuration variables </p></dd> <dt><code class="code">rtags</code></dt> <dd><p>(Unix only) Create Emacs-style tag files from C, R, and Rd files </p></dd> <dt><code class="code">open</code></dt> <dd><p>(Windows only) Open a file via Windows’ file associations </p></dd> <dt><code class="code">texify</code></dt> <dd><p>(Windows only) Process (La)TeX files with R’s style files </p></dd> </dl> <p>Use </p> <div class="example"> <pre class="example-preformatted">R CMD <var class="var">command</var> --help </pre></div> <p>to obtain usage information for each of the tools accessible via the <code class="code">R CMD</code> interface. </p> <p>In addition, you can use options <samp class="option">--arch=</samp>, <samp class="option">--no-environ</samp>, <samp class="option">--no-init-file</samp>, <samp class="option">--no-site-file</samp> and <samp class="option">--vanilla</samp> between <code class="command">R</code> and <code class="command">CMD</code>: these affect any R processes run by the tools. (Here <samp class="option">--vanilla</samp> is equivalent to <samp class="option">--no-environ --no-site-file --no-init-file</samp>.) However, note that <code class="command">R CMD</code> does not of itself use any R startup files (in particular, neither user nor site <samp class="file">Renviron</samp> files), and all of the R processes run by these tools (except <code class="command">BATCH</code>) use <samp class="option">--no-restore</samp>. Most use <samp class="option">--vanilla</samp> and so invoke no R startup files: the current exceptions are <code class="command">INSTALL</code>, <code class="command">REMOVE</code>, <code class="command">Sweave</code> and <code class="command">SHLIB</code> (which uses <samp class="option">--no-site-file --no-init-file</samp>). </p> <div class="example"> <pre class="example-preformatted">R CMD <var class="var">cmd</var> <var class="var">args</var> </pre></div> <p>for any other executable <code class="command"><var class="var">cmd</var></code> on the path or given by an absolute filepath: this is useful to have the same environment as R or the specific commands run under, for example to run <code class="command">ldd</code> or <code class="command">pdflatex</code>. Under Windows <var class="var">cmd</var> can be an executable or a batch file, or if it has extension <code class="code">.sh</code> or <code class="code">.pl</code> the appropriate interpreter (if available) is called to run it. </p> <hr> </div> <div class="appendixsec-level-extent" id="Invoking-R-under-Windows"> <div class="nav-panel"> <p> Next: <a href="#Invoking-R-under-macOS" accesskey="n" rel="next">Invoking R under macOS</a>, Previous: <a href="#Invoking-R-from-the-command-line" accesskey="p" rel="prev">Invoking R from the command line</a>, Up: <a href="#Invoking-R" accesskey="u" rel="up">Invoking R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="appendixsec" id="Invoking-R-under-Windows-1"><span>B.2 Invoking R under Windows<a class="copiable-link" href="#Invoking-R-under-Windows-1"> ¶</a></span></h3> <p>There are two ways to run R under Windows. Within a terminal window (e.g. <code class="code">cmd.exe</code> or a more capable shell), the methods described in the previous section may be used, invoking by <code class="code">R.exe</code> or more directly by <code class="code">Rterm.exe</code>. For interactive use, there is a console-based GUI (<code class="code">Rgui.exe</code>). </p> <p>The startup procedure under Windows is very similar to that under UNIX, but references to the ‘home directory’ need to be clarified, as this is not always defined on Windows. If the environment variable <code class="env">R_USER</code> is defined, that gives the home directory. Next, if the environment variable <code class="env">HOME</code> is defined, that gives the home directory. After those two user-controllable settings, R tries to find system defined home directories. It first tries to use the Windows "personal" directory (typically <code class="code">My Documents</code> in recent versions of Windows). If that fails, and environment variables <code class="env">HOMEDRIVE</code> and <code class="env">HOMEPATH</code> are defined (and they normally are) these define the home directory. Failing all those, the home directory is taken to be the starting directory. </p> <p>You need to ensure that either the environment variables <code class="env">TMPDIR</code>, <code class="env">TMP</code> and <code class="env">TEMP</code> are either unset or one of them points to a valid place to create temporary files and directories. </p> <p>Environment variables can be supplied as ‘<samp class="samp"><var class="var">name</var>=<var class="var">value</var></samp>’ pairs on the command line. </p> <p>If there is an argument ending <samp class="file">.RData</samp> (in any case) it is interpreted as the path to the workspace to be restored: it implies <samp class="option">--restore</samp> and sets the working directory to the parent of the named file. (This mechanism is used for drag-and-drop and file association with <code class="code">RGui.exe</code>, but also works for <code class="code">Rterm.exe</code>. If the named file does not exist it sets the working directory if the parent directory exists.) </p> <p>The following additional command-line options are available when invoking <code class="code">RGui.exe</code>. </p> <dl class="table"> <dt><samp class="option">--mdi</samp></dt> <dt><samp class="option">--sdi</samp></dt> <dt><samp class="option">--no-mdi</samp></dt> <dd><p>Control whether <code class="code">Rgui</code> will operate as an MDI program (with multiple child windows within one main window) or an SDI application (with multiple top-level windows for the console, graphics and pager). The command-line setting overrides the setting in the user’s <samp class="file">Rconsole</samp> file. </p> </dd> <dt><samp class="option">--debug</samp></dt> <dd><p>Enable the “Break to debugger” menu item in <code class="code">Rgui</code>, and trigger a break to the debugger during command line processing. </p></dd> </dl> <p>Under Windows with <code class="code">R CMD</code> you may also specify your own <samp class="file">.bat</samp>, <samp class="file">.exe</samp>, <samp class="file">.sh</samp> or <samp class="file">.pl</samp> file. It will be run under the appropriate interpreter (Perl for <samp class="file">.pl</samp>) with several environment variables set appropriately, including <code class="env">R_HOME</code>, <code class="env">R_OSTYPE</code>, <code class="env">PATH</code>, <code class="env">BSTINPUTS</code> and <code class="env">TEXINPUTS</code>. For example, if you already have <samp class="file">latex.exe</samp> on your path, then </p> <div class="example"> <pre class="example-preformatted">R CMD latex.exe mydoc </pre></div> <p>will run LaTeX on <samp class="file">mydoc.tex</samp>, with the path to R’s <samp class="file">share/texmf</samp> macros appended to <code class="env">TEXINPUTS</code>. (Unfortunately, this does not help with the MiKTeX build of LaTeX, but <code class="command">R CMD texify mydoc</code> will work in that case.) </p> <hr> </div> <div class="appendixsec-level-extent" id="Invoking-R-under-macOS"> <div class="nav-panel"> <p> Next: <a href="#Scripting-with-R" accesskey="n" rel="next">Scripting with R</a>, Previous: <a href="#Invoking-R-under-Windows" accesskey="p" rel="prev">Invoking R under Windows</a>, Up: <a href="#Invoking-R" accesskey="u" rel="up">Invoking R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="appendixsec" id="Invoking-R-under-macOS-1"><span>B.3 Invoking R under macOS<a class="copiable-link" href="#Invoking-R-under-macOS-1"> ¶</a></span></h3> <p>There are two ways to run R under macOS. Within a <code class="code">Terminal.app</code> window by invoking <code class="code">R</code>, the methods described in the first subsection apply. There is also console-based GUI (<code class="code">R.app</code>) that by default is installed in the <code class="code">Applications</code> folder on your system. It is a standard double-clickable macOS application. </p> <p>The startup procedure under macOS is very similar to that under UNIX, but <code class="code">R.app</code> does not make use of command-line arguments. The ‘home directory’ is the one inside the R.framework, but the startup and current working directory are set as the user’s home directory unless a different startup directory is given in the Preferences window accessible from within the GUI. </p> <hr> </div> <div class="appendixsec-level-extent" id="Scripting-with-R"> <div class="nav-panel"> <p> Previous: <a href="#Invoking-R-under-macOS" accesskey="p" rel="prev">Invoking R under macOS</a>, Up: <a href="#Invoking-R" accesskey="u" rel="up">Invoking R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h3 class="appendixsec" id="Scripting-with-R-1"><span>B.4 Scripting with R<a class="copiable-link" href="#Scripting-with-R-1"> ¶</a></span></h3> <p>If you just want to run a file <samp class="file">foo.R</samp> of R commands, the recommended way is to use <code class="command">R CMD BATCH foo.R</code>. If you want to run this in the background or as a batch job use OS-specific facilities to do so: for example in most shells on Unix-alike OSes <code class="command">R CMD BATCH foo.R &</code> runs a background job. </p> <p>You can pass parameters to scripts via additional arguments on the command line: for example (where the exact quoting needed will depend on the shell in use) </p> <div class="example"> <pre class="example-preformatted">R CMD BATCH "--args arg1 arg2" foo.R & </pre></div> <p>will pass arguments to a script which can be retrieved as a character vector by </p> <div class="example"> <pre class="example-preformatted">args <- commandArgs(TRUE) </pre></div> <p>This is made simpler by the alternative front-end <code class="command">Rscript</code>, which can be invoked by </p> <div class="example"> <pre class="example-preformatted">Rscript foo.R arg1 arg2 </pre></div> <p>and this can also be used to write executable script files like (at least on Unix-alikes, and in some Windows shells) </p> <div class="example"> <pre class="example-preformatted">#! /path/to/Rscript args <- commandArgs(TRUE) ... q(status=<exit status code>) </pre></div> <p>If this is entered into a text file <samp class="file">runfoo</samp> and this is made executable (by <code class="command">chmod 755 runfoo</code>), it can be invoked for different arguments by </p> <div class="example"> <pre class="example-preformatted">runfoo arg1 arg2 </pre></div> <p>For further options see <code class="command">help("Rscript")</code>. This writes R output to <samp class="file">stdout</samp> and <samp class="file">stderr</samp>, and this can be redirected in the usual way for the shell running the command. </p> <p>If you do not wish to hardcode the path to <code class="command">Rscript</code> but have it in your path (which is normally the case for an installed R except on Windows, but e.g. macOS users may need to add <samp class="file">/usr/local/bin</samp> to their path), use </p> <div class="example"> <pre class="example-preformatted">#! /usr/bin/env Rscript ... </pre></div> <p>At least in Bourne and bash shells, the <code class="code">#!</code> mechanism does <strong class="strong">not</strong> allow extra arguments like <code class="code">#! /usr/bin/env Rscript --vanilla</code>. </p> <p>One thing to consider is what <code class="code">stdin()</code> refers to. It is commonplace to write R scripts with segments like </p> <div class="example"> <pre class="example-preformatted">chem <- scan(n=24) 2.90 3.10 3.40 3.40 3.70 3.70 2.80 2.50 2.40 2.40 2.70 2.20 5.28 3.37 3.03 3.03 28.95 3.77 3.40 2.20 3.50 3.60 3.70 3.70 </pre></div> <p>and <code class="code">stdin()</code> refers to the script file to allow such traditional usage. If you want to refer to the process’s <samp class="file">stdin</samp>, use <code class="code">"stdin"</code> as a <code class="code">file</code> connection, e.g. <code class="code">scan("stdin", ...)</code>. </p> <p>Another way to write executable script files (suggested by François Pinard) is to use a <em class="emph">here document</em> like </p> <div class="example"> <pre class="example-preformatted">#!/bin/sh [environment variables can be set here] R --no-echo [other options] <<EOF R program goes here... EOF </pre></div> <p>but here <code class="code">stdin()</code> refers to the program source and <code class="code">"stdin"</code> will not be usable. </p> <p>Short scripts can be passed to <code class="command">Rscript</code> on the command-line <em class="emph">via</em> the <samp class="option">-e</samp> flag. (Empty scripts are not accepted.) </p> <p>Note that on a Unix-alike the input filename (such as <samp class="file">foo.R</samp>) should not contain spaces nor shell metacharacters. </p> <hr> </div> </div> <div class="appendix-level-extent" id="The-command_002dline-editor"> <div class="nav-panel"> <p> Next: <a href="#Function-and-variable-index" accesskey="n" rel="next">Function and variable index</a>, Previous: <a href="#Invoking-R" accesskey="p" rel="prev">Invoking R</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="appendix" id="The-command_002dline-editor-1"><span>Appendix C The command-line editor<a class="copiable-link" href="#The-command_002dline-editor-1"> ¶</a></span></h2> <ul class="mini-toc"> <li><a href="#Preliminaries" accesskey="1">Preliminaries</a></li> <li><a href="#Editing-actions" accesskey="2">Editing actions</a></li> <li><a href="#Command_002dline-editor-summary" accesskey="3">Command-line editor summary</a></li> </ul> <div class="appendixsection-level-extent" id="Preliminaries"> <h3 class="appendixsection"><span>C.1 Preliminaries<a class="copiable-link" href="#Preliminaries"> ¶</a></span></h3> <p>When the <abbr class="acronym">GNU</abbr> <strong class="strong">readline</strong> library is available at the time R is configured for compilation under UNIX, an inbuilt command line editor allowing recall, editing and re-submission of prior commands is used. Note that other versions of <strong class="strong">readline</strong> exist and may be used by the inbuilt command line editor: this is most common on macOS. You can find out which version (if any) is available by running <code class="code">extSoftVersion()</code> in an R session. </p> <p>It can be disabled (useful for usage with <abbr class="acronym">ESS</abbr> <a class="footnote" id="DOCF25" href="#FOOT25"><sup>25</sup></a>) using the startup option <samp class="option">--no-readline</samp>. </p> <p>Windows versions of R have somewhat simpler command-line editing: see ‘<samp class="samp">Console</samp>’ under the ‘<samp class="samp">Help</samp>’ menu of the <abbr class="acronym">GUI</abbr>, and the file <samp class="file">README.Rterm</samp> for command-line editing under <code class="code">Rterm.exe</code>. </p> <p>When using R with GNU<a class="footnote" id="DOCF26" href="#FOOT26"><sup>26</sup></a> <strong class="strong">readline</strong> capabilities, the functions described below are available, as well as others (probably) documented in <code class="command">man readline</code> or <code class="command">info readline</code> on your system. </p> <p>Many of these use either Control or Meta characters. Control characters, such as <kbd class="kbd">Control-m</kbd>, are obtained by holding the <kbd class="key">CTRL</kbd> down while you press the <kbd class="key">m</kbd> key, and are written as <kbd class="kbd">C-m</kbd> below. Meta characters, such as <kbd class="kbd">Meta-b</kbd>, are typed by holding down <kbd class="key">META</kbd><a class="footnote" id="DOCF27" href="#FOOT27"><sup>27</sup></a> and pressing <kbd class="key">b</kbd>, and written as <kbd class="kbd">M-b</kbd> in the following. If your terminal does not have a <kbd class="key">META</kbd> key enabled, you can still type Meta characters using two-character sequences starting with <kbd class="kbd">ESC</kbd>. Thus, to enter <kbd class="kbd">M-b</kbd>, you could type <kbd class="key">ESC</kbd><kbd class="key">b</kbd>. The <kbd class="kbd">ESC</kbd> character sequences are also allowed on terminals with real Meta keys. Note that case is significant for Meta characters. </p> <p>Some but not all versions<a class="footnote" id="DOCF28" href="#FOOT28"><sup>28</sup></a> of <strong class="strong">readline</strong> will recognize resizing of the terminal window so this is best avoided. </p> </div> <div class="appendixsection-level-extent" id="Editing-actions"> <h3 class="appendixsection"><span>C.2 Editing actions<a class="copiable-link" href="#Editing-actions"> ¶</a></span></h3> <p>The R program keeps a history of the command lines you type, including the erroneous lines, and commands in your history may be recalled, changed if necessary, and re-submitted as new commands. In Emacs-style command-line editing any straight typing you do while in this editing phase causes the characters to be inserted in the command you are editing, displacing any characters to the right of the cursor. In <em class="emph">vi</em> mode character insertion mode is started by <kbd class="kbd">M-i</kbd> or <kbd class="kbd">M-a</kbd>, characters are typed and insertion mode is finished by typing a further <kbd class="key">ESC</kbd>. (The default is Emacs-style, and only that is described here: for <em class="emph">vi</em> mode see the <strong class="strong">readline</strong> documentation.) </p> <p>Pressing the <kbd class="key">RET</kbd> command at any time causes the command to be re-submitted. </p> <p>Other editing actions are summarized in the following table. </p> </div> <div class="appendixsection-level-extent" id="Command_002dline-editor-summary"> <h3 class="appendixsection"><span>C.3 Command-line editor summary<a class="copiable-link" href="#Command_002dline-editor-summary"> ¶</a></span></h3> <h4 class="subheading" id="Command-recall-and-vertical-motion"><span>Command recall and vertical motion<a class="copiable-link" href="#Command-recall-and-vertical-motion"> ¶</a></span></h4> <dl class="table"> <dt><kbd class="kbd">C-p</kbd></dt> <dd><p>Go to the previous command (backwards in the history). </p></dd> <dt><kbd class="kbd">C-n</kbd></dt> <dd><p>Go to the next command (forwards in the history). </p></dd> <dt><kbd class="kbd">C-r <var class="var">text</var></kbd></dt> <dd><p>Find the last command with the <var class="var">text</var> string in it. This can be cancelled by <code class="code">C-g</code> (and on some versions of R by <code class="code">C-c</code>). </p></dd> </dl> <p>On most terminals, you can also use the up and down arrow keys instead of <kbd class="kbd">C-p</kbd> and <kbd class="kbd">C-n</kbd>, respectively. </p> <h4 class="subheading" id="Horizontal-motion-of-the-cursor"><span>Horizontal motion of the cursor<a class="copiable-link" href="#Horizontal-motion-of-the-cursor"> ¶</a></span></h4> <dl class="table"> <dt><kbd class="kbd">C-a</kbd></dt> <dd><p>Go to the beginning of the command. </p></dd> <dt><kbd class="kbd">C-e</kbd></dt> <dd><p>Go to the end of the line. </p></dd> <dt><kbd class="kbd">M-b</kbd></dt> <dd><p>Go back one word. </p></dd> <dt><kbd class="kbd">M-f</kbd></dt> <dd><p>Go forward one word. </p></dd> <dt><kbd class="kbd">C-b</kbd></dt> <dd><p>Go back one character. </p></dd> <dt><kbd class="kbd">C-f</kbd></dt> <dd><p>Go forward one character. </p></dd> </dl> <p>On most terminals, you can also use the left and right arrow keys instead of <kbd class="kbd">C-b</kbd> and <kbd class="kbd">C-f</kbd>, respectively. </p> <h4 class="subheading" id="Editing-and-re_002dsubmission"><span>Editing and re-submission<a class="copiable-link" href="#Editing-and-re_002dsubmission"> ¶</a></span></h4> <dl class="table"> <dt><kbd class="kbd"><var class="var">text</var></kbd></dt> <dd><p>Insert <var class="var">text</var> at the cursor. </p></dd> <dt><kbd class="kbd">C-f <var class="var">text</var></kbd></dt> <dd><p>Append <var class="var">text</var> after the cursor. </p></dd> <dt><kbd class="kbd"><kbd class="key">DEL</kbd></kbd></dt> <dd><p>Delete the previous character (left of the cursor). </p></dd> <dt><kbd class="kbd">C-d</kbd></dt> <dd><p>Delete the character under the cursor. </p></dd> <dt><kbd class="kbd">M-d</kbd></dt> <dd><p>Delete the rest of the word under the cursor, and “save” it. </p></dd> <dt><kbd class="kbd">C-k</kbd></dt> <dd><p>Delete from cursor to end of command, and “save” it. </p></dd> <dt><kbd class="kbd">C-y</kbd></dt> <dd><p>Insert (yank) the last “saved” text here. </p></dd> <dt><kbd class="kbd">C-t</kbd></dt> <dd><p>Transpose the character under the cursor with the next. </p></dd> <dt><kbd class="kbd">M-l</kbd></dt> <dd><p>Change the rest of the word to lower case. </p></dd> <dt><kbd class="kbd">M-c</kbd></dt> <dd><p>Change the rest of the word to upper case. </p></dd> <dt><kbd class="kbd"><kbd class="key">RET</kbd></kbd></dt> <dd><p>Re-submit the command to R. </p></dd> </dl> <p>The final <kbd class="key">RET</kbd> terminates the command line editing sequence. </p> <p>The <strong class="strong">readline</strong> key bindings can be customized in the usual way <em class="emph">via</em> a <samp class="file">~/.inputrc</samp> file. These customizations can be conditioned on application <code class="code">R</code>, that is by including a section like </p> <div class="example"> <pre class="example-preformatted">$if R "\C-xd": "q('no')\n" $endif </pre></div> <hr> </div> </div> <div class="appendix-level-extent" id="Function-and-variable-index"> <div class="nav-panel"> <p> Next: <a href="#Concept-index" accesskey="n" rel="next">Concept index</a>, Previous: <a href="#The-command_002dline-editor" accesskey="p" rel="prev">The command-line editor</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="appendix" id="Function-and-variable-index-1"><span>Appendix D Function and variable index<a class="copiable-link" href="#Function-and-variable-index-1"> ¶</a></span></h2> <div class="printindex vr-printindex"> <table summary="" class="vr-letters-header-printindex"><tr><th>Jump to: </th><td><a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-1"><b>-</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-2"><b>:</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-3"><b>!</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-4"><b>?</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-5"><b>.</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-6"><b>*</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-7"><b>/</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-8"><b>&</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-9"><b>%</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-10"><b>^</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-11"><b>+</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-12"><b><</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-13"><b>=</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-14"><b>></b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-15"><b>|</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-16"><b>~</b></a> <br> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-A"><b>A</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-B"><b>B</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-C"><b>C</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-D"><b>D</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-E"><b>E</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-F"><b>F</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-G"><b>G</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-H"><b>H</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-I"><b>I</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-J"><b>J</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-K"><b>K</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-L"><b>L</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-M"><b>M</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-N"><b>N</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-O"><b>O</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-P"><b>P</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-Q"><b>Q</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-R"><b>R</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-S"><b>S</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-T"><b>T</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-U"><b>U</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-V"><b>V</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-W"><b>W</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-X"><b>X</b></a> </td></tr></table> <table summary="" class="vr-entries-printindex" border="0"> <tr><td></td><th class="entries-header-printindex">Index Entry</th><th class="sections-header-printindex">Section</th></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-1">-</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_002d"><code>-</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-2">:</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_003a"><code>:</code></a></td><td class="printindex-index-section"><a href="#Generating-regular-sequences">Generating regular sequences</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_003a_003a"><code>::</code></a></td><td class="printindex-index-section"><a href="#Namespaces">Namespaces</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_003a_003a_003a"><code>:::</code></a></td><td class="printindex-index-section"><a href="#Namespaces">Namespaces</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-3">!</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_0021"><code>!</code></a></td><td class="printindex-index-section"><a href="#Logical-vectors">Logical vectors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_0021_003d"><code>!=</code></a></td><td class="printindex-index-section"><a href="#Logical-vectors">Logical vectors</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-4">?</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_003f"><code>?</code></a></td><td class="printindex-index-section"><a href="#Getting-help">Getting help</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_003f_003f"><code>??</code></a></td><td class="printindex-index-section"><a href="#Getting-help">Getting help</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-5">.</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_002e"><code>.</code></a></td><td class="printindex-index-section"><a href="#Updating-fitted-models">Updating fitted models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_002eFirst"><code>.First</code></a></td><td class="printindex-index-section"><a href="#Customizing-the-environment">Customizing the environment</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_002eLast"><code>.Last</code></a></td><td class="printindex-index-section"><a href="#Customizing-the-environment">Customizing the environment</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-6">*</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_002a"><code>*</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-7">/</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_002f"><code>/</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-8">&</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_0026"><code>&</code></a></td><td class="printindex-index-section"><a href="#Logical-vectors">Logical vectors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_0026_0026"><code>&&</code></a></td><td class="printindex-index-section"><a href="#Conditional-execution">Conditional execution</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-9">%</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_0025_002a_0025"><code>%*%</code></a></td><td class="printindex-index-section"><a href="#Multiplication">Multiplication</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_0025o_0025"><code>%o%</code></a></td><td class="printindex-index-section"><a href="#The-outer-product-of-two-arrays">The outer product of two arrays</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-10">^</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_005e"><code>^</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-11">+</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_002b"><code>+</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-12"><</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_003c"><code><</code></a></td><td class="printindex-index-section"><a href="#Logical-vectors">Logical vectors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_003c_003c_002d"><code><<-</code></a></td><td class="printindex-index-section"><a href="#Scope">Scope</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_003c_003d"><code><=</code></a></td><td class="printindex-index-section"><a href="#Logical-vectors">Logical vectors</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-13">=</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_003d_003d"><code>==</code></a></td><td class="printindex-index-section"><a href="#Logical-vectors">Logical vectors</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-14">></th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_003e"><code>></code></a></td><td class="printindex-index-section"><a href="#Logical-vectors">Logical vectors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_003e_003d"><code>>=</code></a></td><td class="printindex-index-section"><a href="#Logical-vectors">Logical vectors</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-15">|</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_007c"><code>|</code></a></td><td class="printindex-index-section"><a href="#Logical-vectors">Logical vectors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_007c_007c"><code>||</code></a></td><td class="printindex-index-section"><a href="#Conditional-execution">Conditional execution</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_symbol-16">~</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-_007e"><code>~</code></a></td><td class="printindex-index-section"><a href="#Formulae-for-statistical-models">Formulae for statistical models</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-A">A</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-abline"><code>abline</code></a></td><td class="printindex-index-section"><a href="#Low_002dlevel-plotting-commands">Low-level plotting commands</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-ace"><code>ace</code></a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-add1"><code>add1</code></a></td><td class="printindex-index-section"><a href="#Updating-fitted-models">Updating fitted models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-anova"><code>anova</code></a></td><td class="printindex-index-section"><a href="#Generic-functions-for-extracting-model-information">Generic functions for extracting model information</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-anova-1"><code>anova</code></a></td><td class="printindex-index-section"><a href="#ANOVA-tables">ANOVA tables</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-aov"><code>aov</code></a></td><td class="printindex-index-section"><a href="#Analysis-of-variance-and-model-comparison">Analysis of variance and model comparison</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-aperm"><code>aperm</code></a></td><td class="printindex-index-section"><a href="#Generalized-transpose-of-an-array">Generalized transpose of an array</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-array"><code>array</code></a></td><td class="printindex-index-section"><a href="#The-array_0028_0029-function">The array() function</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-as_002edata_002eframe"><code>as.data.frame</code></a></td><td class="printindex-index-section"><a href="#Making-data-frames">Making data frames</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-as_002evector"><code>as.vector</code></a></td><td class="printindex-index-section"><a href="#The-concatenation-function-c_0028_0029-with-arrays">The concatenation function c() with arrays</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-attach"><code>attach</code></a></td><td class="printindex-index-section"><a href="#attach_0028_0029-and-detach_0028_0029">attach() and detach()</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-attr"><code>attr</code></a></td><td class="printindex-index-section"><a href="#Getting-and-setting-attributes">Getting and setting attributes</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-attr-1"><code>attr</code></a></td><td class="printindex-index-section"><a href="#Getting-and-setting-attributes">Getting and setting attributes</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-attributes"><code>attributes</code></a></td><td class="printindex-index-section"><a href="#Getting-and-setting-attributes">Getting and setting attributes</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-attributes-1"><code>attributes</code></a></td><td class="printindex-index-section"><a href="#Getting-and-setting-attributes">Getting and setting attributes</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-avas"><code>avas</code></a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-axis"><code>axis</code></a></td><td class="printindex-index-section"><a href="#Low_002dlevel-plotting-commands">Low-level plotting commands</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-B">B</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-boxplot"><code>boxplot</code></a></td><td class="printindex-index-section"><a href="#One_002d-and-two_002dsample-tests">One- and two-sample tests</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-break"><code>break</code></a></td><td class="printindex-index-section"><a href="#Repetitive-execution">Repetitive execution</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-bruto"><code>bruto</code></a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-C">C</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-c"><code>c</code></a></td><td class="printindex-index-section"><a href="#Vectors-and-assignment">Vectors and assignment</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-c-1"><code>c</code></a></td><td class="printindex-index-section"><a href="#Character-vectors">Character vectors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-c-2"><code>c</code></a></td><td class="printindex-index-section"><a href="#The-concatenation-function-c_0028_0029-with-arrays">The concatenation function c() with arrays</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-c-3"><code>c</code></a></td><td class="printindex-index-section"><a href="#Concatenating-lists">Concatenating lists</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-C"><code>C</code></a></td><td class="printindex-index-section"><a href="#Contrasts">Contrasts</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-cbind"><code>cbind</code></a></td><td class="printindex-index-section"><a href="#Forming-partitioned-matrices">Forming partitioned matrices</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-coef"><code>coef</code></a></td><td class="printindex-index-section"><a href="#Generic-functions-for-extracting-model-information">Generic functions for extracting model information</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-coefficients"><code>coefficients</code></a></td><td class="printindex-index-section"><a href="#Generic-functions-for-extracting-model-information">Generic functions for extracting model information</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-contour"><code>contour</code></a></td><td class="printindex-index-section"><a href="#Display-graphics">Display graphics</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-contrasts"><code>contrasts</code></a></td><td class="printindex-index-section"><a href="#Contrasts">Contrasts</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-coplot"><code>coplot</code></a></td><td class="printindex-index-section"><a href="#Displaying-multivariate-data">Displaying multivariate data</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-cos"><code>cos</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-crossprod"><code>crossprod</code></a></td><td class="printindex-index-section"><a href="#Index-matrices">Index matrices</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-crossprod-1"><code>crossprod</code></a></td><td class="printindex-index-section"><a href="#Multiplication">Multiplication</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-cut"><code>cut</code></a></td><td class="printindex-index-section"><a href="#Frequency-tables-from-factors">Frequency tables from factors</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-D">D</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-data"><code>data</code></a></td><td class="printindex-index-section"><a href="#Accessing-builtin-datasets">Accessing builtin datasets</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-data_002eframe"><code>data.frame</code></a></td><td class="printindex-index-section"><a href="#Making-data-frames">Making data frames</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-density"><code>density</code></a></td><td class="printindex-index-section"><a href="#Examining-the-distribution-of-a-set-of-data">Examining the distribution of a set of data</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-det"><code>det</code></a></td><td class="printindex-index-section"><a href="#Singular-value-decomposition-and-determinants">Singular value decomposition and determinants</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-detach"><code>detach</code></a></td><td class="printindex-index-section"><a href="#attach_0028_0029-and-detach_0028_0029">attach() and detach()</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-determinant"><code>determinant</code></a></td><td class="printindex-index-section"><a href="#Singular-value-decomposition-and-determinants">Singular value decomposition and determinants</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-dev_002elist"><code>dev.list</code></a></td><td class="printindex-index-section"><a href="#Multiple-graphics-devices">Multiple graphics devices</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-dev_002enext"><code>dev.next</code></a></td><td class="printindex-index-section"><a href="#Multiple-graphics-devices">Multiple graphics devices</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-dev_002eoff"><code>dev.off</code></a></td><td class="printindex-index-section"><a href="#Multiple-graphics-devices">Multiple graphics devices</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-dev_002eprev"><code>dev.prev</code></a></td><td class="printindex-index-section"><a href="#Multiple-graphics-devices">Multiple graphics devices</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-dev_002eset"><code>dev.set</code></a></td><td class="printindex-index-section"><a href="#Multiple-graphics-devices">Multiple graphics devices</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-deviance"><code>deviance</code></a></td><td class="printindex-index-section"><a href="#Generic-functions-for-extracting-model-information">Generic functions for extracting model information</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-diag"><code>diag</code></a></td><td class="printindex-index-section"><a href="#Multiplication">Multiplication</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-dim"><code>dim</code></a></td><td class="printindex-index-section"><a href="#Arrays">Arrays</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-dotchart"><code>dotchart</code></a></td><td class="printindex-index-section"><a href="#Display-graphics">Display graphics</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-drop1"><code>drop1</code></a></td><td class="printindex-index-section"><a href="#Updating-fitted-models">Updating fitted models</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-E">E</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-ecdf"><code>ecdf</code></a></td><td class="printindex-index-section"><a href="#Examining-the-distribution-of-a-set-of-data">Examining the distribution of a set of data</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-edit"><code>edit</code></a></td><td class="printindex-index-section"><a href="#Editing-data">Editing data</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-eigen"><code>eigen</code></a></td><td class="printindex-index-section"><a href="#Eigenvalues-and-eigenvectors">Eigenvalues and eigenvectors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-else"><code>else</code></a></td><td class="printindex-index-section"><a href="#Conditional-execution">Conditional execution</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Error"><code>Error</code></a></td><td class="printindex-index-section"><a href="#Analysis-of-variance-and-model-comparison">Analysis of variance and model comparison</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-example"><code>example</code></a></td><td class="printindex-index-section"><a href="#Getting-help">Getting help</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-exp"><code>exp</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-F">F</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-F"><code>F</code></a></td><td class="printindex-index-section"><a href="#Logical-vectors">Logical vectors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-factor"><code>factor</code></a></td><td class="printindex-index-section"><a href="#Factors">Factors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-FALSE"><code>FALSE</code></a></td><td class="printindex-index-section"><a href="#Logical-vectors">Logical vectors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-fivenum"><code>fivenum</code></a></td><td class="printindex-index-section"><a href="#Examining-the-distribution-of-a-set-of-data">Examining the distribution of a set of data</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-for"><code>for</code></a></td><td class="printindex-index-section"><a href="#Repetitive-execution">Repetitive execution</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-formula"><code>formula</code></a></td><td class="printindex-index-section"><a href="#Generic-functions-for-extracting-model-information">Generic functions for extracting model information</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-function"><code>function</code></a></td><td class="printindex-index-section"><a href="#Writing-your-own-functions">Writing your own functions</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-G">G</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-getAnywhere"><code>getAnywhere</code></a></td><td class="printindex-index-section"><a href="#Object-orientation">Object orientation</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-getS3method"><code>getS3method</code></a></td><td class="printindex-index-section"><a href="#Object-orientation">Object orientation</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-glm"><code>glm</code></a></td><td class="printindex-index-section"><a href="#The-glm_0028_0029-function">The glm() function</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-H">H</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-help"><code>help</code></a></td><td class="printindex-index-section"><a href="#Getting-help">Getting help</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-help-1"><code>help</code></a></td><td class="printindex-index-section"><a href="#Getting-help">Getting help</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-help_002esearch"><code>help.search</code></a></td><td class="printindex-index-section"><a href="#Getting-help">Getting help</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-help_002estart"><code>help.start</code></a></td><td class="printindex-index-section"><a href="#Getting-help">Getting help</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-hist"><code>hist</code></a></td><td class="printindex-index-section"><a href="#Examining-the-distribution-of-a-set-of-data">Examining the distribution of a set of data</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-hist-1"><code>hist</code></a></td><td class="printindex-index-section"><a href="#Display-graphics">Display graphics</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-I">I</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-identify"><code>identify</code></a></td><td class="printindex-index-section"><a href="#Interacting-with-graphics">Interacting with graphics</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-if"><code>if</code></a></td><td class="printindex-index-section"><a href="#Conditional-execution">Conditional execution</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-if-1"><code>if</code></a></td><td class="printindex-index-section"><a href="#Conditional-execution">Conditional execution</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-ifelse"><code>ifelse</code></a></td><td class="printindex-index-section"><a href="#Conditional-execution">Conditional execution</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-image"><code>image</code></a></td><td class="printindex-index-section"><a href="#Display-graphics">Display graphics</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-is_002ena"><code>is.na</code></a></td><td class="printindex-index-section"><a href="#Missing-values">Missing values</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-is_002enan"><code>is.nan</code></a></td><td class="printindex-index-section"><a href="#Missing-values">Missing values</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-J">J</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-jpeg"><code>jpeg</code></a></td><td class="printindex-index-section"><a href="#Device-drivers">Device drivers</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-K">K</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-ks_002etest"><code>ks.test</code></a></td><td class="printindex-index-section"><a href="#Examining-the-distribution-of-a-set-of-data">Examining the distribution of a set of data</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-L">L</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-legend"><code>legend</code></a></td><td class="printindex-index-section"><a href="#Low_002dlevel-plotting-commands">Low-level plotting commands</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-length"><code>length</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-length-1"><code>length</code></a></td><td class="printindex-index-section"><a href="#The-intrinsic-attributes-mode-and-length">The intrinsic attributes mode and length</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-levels"><code>levels</code></a></td><td class="printindex-index-section"><a href="#Factors">Factors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-lines"><code>lines</code></a></td><td class="printindex-index-section"><a href="#Low_002dlevel-plotting-commands">Low-level plotting commands</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-list"><code>list</code></a></td><td class="printindex-index-section"><a href="#Lists">Lists</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-lm"><code>lm</code></a></td><td class="printindex-index-section"><a href="#Linear-models">Linear models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-lme"><code>lme</code></a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-locator"><code>locator</code></a></td><td class="printindex-index-section"><a href="#Interacting-with-graphics">Interacting with graphics</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-loess"><code>loess</code></a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-loess-1"><code>loess</code></a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-log"><code>log</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-lqs"><code>lqs</code></a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-lsfit"><code>lsfit</code></a></td><td class="printindex-index-section"><a href="#Least-squares-fitting-and-the-QR-decomposition">Least squares fitting and the QR decomposition</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-M">M</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-mars"><code>mars</code></a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-max"><code>max</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-mean"><code>mean</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-methods"><code>methods</code></a></td><td class="printindex-index-section"><a href="#Object-orientation">Object orientation</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-min"><code>min</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-mode"><code>mode</code></a></td><td class="printindex-index-section"><a href="#The-intrinsic-attributes-mode-and-length">The intrinsic attributes mode and length</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-N">N</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-NA"><code>NA</code></a></td><td class="printindex-index-section"><a href="#Missing-values">Missing values</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-NaN"><code>NaN</code></a></td><td class="printindex-index-section"><a href="#Missing-values">Missing values</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-ncol"><code>ncol</code></a></td><td class="printindex-index-section"><a href="#Matrix-facilities">Matrix facilities</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-next"><code>next</code></a></td><td class="printindex-index-section"><a href="#Repetitive-execution">Repetitive execution</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-nlm"><code>nlm</code></a></td><td class="printindex-index-section"><a href="#Nonlinear-least-squares-and-maximum-likelihood-models">Nonlinear least squares and maximum likelihood models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-nlm-1"><code>nlm</code></a></td><td class="printindex-index-section"><a href="#Least-squares">Least squares</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-nlm-2"><code>nlm</code></a></td><td class="printindex-index-section"><a href="#Maximum-likelihood">Maximum likelihood</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-nlme"><code>nlme</code></a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-nlminb"><code>nlminb</code></a></td><td class="printindex-index-section"><a href="#Nonlinear-least-squares-and-maximum-likelihood-models">Nonlinear least squares and maximum likelihood models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-nrow"><code>nrow</code></a></td><td class="printindex-index-section"><a href="#Matrix-facilities">Matrix facilities</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-O">O</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-optim"><code>optim</code></a></td><td class="printindex-index-section"><a href="#Nonlinear-least-squares-and-maximum-likelihood-models">Nonlinear least squares and maximum likelihood models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-order"><code>order</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-ordered"><code>ordered</code></a></td><td class="printindex-index-section"><a href="#Ordered-factors">Ordered factors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-ordered-1"><code>ordered</code></a></td><td class="printindex-index-section"><a href="#Ordered-factors">Ordered factors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-outer"><code>outer</code></a></td><td class="printindex-index-section"><a href="#The-outer-product-of-two-arrays">The outer product of two arrays</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-P">P</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-pairs"><code>pairs</code></a></td><td class="printindex-index-section"><a href="#Displaying-multivariate-data">Displaying multivariate data</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-par"><code>par</code></a></td><td class="printindex-index-section"><a href="#The-par_0028_0029-function">The par() function</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-paste"><code>paste</code></a></td><td class="printindex-index-section"><a href="#Character-vectors">Character vectors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-pdf"><code>pdf</code></a></td><td class="printindex-index-section"><a href="#Device-drivers">Device drivers</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-persp"><code>persp</code></a></td><td class="printindex-index-section"><a href="#Display-graphics">Display graphics</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-plot"><code>plot</code></a></td><td class="printindex-index-section"><a href="#Generic-functions-for-extracting-model-information">Generic functions for extracting model information</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-plot-1"><code>plot</code></a></td><td class="printindex-index-section"><a href="#The-plot_0028_0029-function">The plot() function</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-pmax"><code>pmax</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-pmin"><code>pmin</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-png"><code>png</code></a></td><td class="printindex-index-section"><a href="#Device-drivers">Device drivers</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-points"><code>points</code></a></td><td class="printindex-index-section"><a href="#Low_002dlevel-plotting-commands">Low-level plotting commands</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-polygon"><code>polygon</code></a></td><td class="printindex-index-section"><a href="#Low_002dlevel-plotting-commands">Low-level plotting commands</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-postscript"><code>postscript</code></a></td><td class="printindex-index-section"><a href="#Device-drivers">Device drivers</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-predict"><code>predict</code></a></td><td class="printindex-index-section"><a href="#Generic-functions-for-extracting-model-information">Generic functions for extracting model information</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-print"><code>print</code></a></td><td class="printindex-index-section"><a href="#Generic-functions-for-extracting-model-information">Generic functions for extracting model information</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-prod"><code>prod</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-Q">Q</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-qqline"><code>qqline</code></a></td><td class="printindex-index-section"><a href="#Examining-the-distribution-of-a-set-of-data">Examining the distribution of a set of data</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-qqline-1"><code>qqline</code></a></td><td class="printindex-index-section"><a href="#Display-graphics">Display graphics</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-qqnorm"><code>qqnorm</code></a></td><td class="printindex-index-section"><a href="#Examining-the-distribution-of-a-set-of-data">Examining the distribution of a set of data</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-qqnorm-1"><code>qqnorm</code></a></td><td class="printindex-index-section"><a href="#Display-graphics">Display graphics</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-qqplot"><code>qqplot</code></a></td><td class="printindex-index-section"><a href="#Display-graphics">Display graphics</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-qr"><code>qr</code></a></td><td class="printindex-index-section"><a href="#Least-squares-fitting-and-the-QR-decomposition">Least squares fitting and the QR decomposition</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-quartz"><code>quartz</code></a></td><td class="printindex-index-section"><a href="#Device-drivers">Device drivers</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-R">R</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-range"><code>range</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-rbind"><code>rbind</code></a></td><td class="printindex-index-section"><a href="#Forming-partitioned-matrices">Forming partitioned matrices</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-read_002etable"><code>read.table</code></a></td><td class="printindex-index-section"><a href="#The-read_002etable_0028_0029-function">The read.table() function</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-rep"><code>rep</code></a></td><td class="printindex-index-section"><a href="#Generating-regular-sequences">Generating regular sequences</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-repeat"><code>repeat</code></a></td><td class="printindex-index-section"><a href="#Repetitive-execution">Repetitive execution</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-resid"><code>resid</code></a></td><td class="printindex-index-section"><a href="#Generic-functions-for-extracting-model-information">Generic functions for extracting model information</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-residuals"><code>residuals</code></a></td><td class="printindex-index-section"><a href="#Generic-functions-for-extracting-model-information">Generic functions for extracting model information</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-rlm"><code>rlm</code></a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-rm"><code>rm</code></a></td><td class="printindex-index-section"><a href="#Data-permanency-and-removing-objects">Data permanency and removing objects</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-S">S</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-scan"><code>scan</code></a></td><td class="printindex-index-section"><a href="#The-scan_0028_0029-function">The scan() function</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-sd"><code>sd</code></a></td><td class="printindex-index-section"><a href="#The-function-tapply_0028_0029-and-ragged-arrays">The function tapply() and ragged arrays</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-search"><code>search</code></a></td><td class="printindex-index-section"><a href="#Managing-the-search-path">Managing the search path</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-seq"><code>seq</code></a></td><td class="printindex-index-section"><a href="#Generating-regular-sequences">Generating regular sequences</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-shapiro_002etest"><code>shapiro.test</code></a></td><td class="printindex-index-section"><a href="#Examining-the-distribution-of-a-set-of-data">Examining the distribution of a set of data</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-sin"><code>sin</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-sink"><code>sink</code></a></td><td class="printindex-index-section"><a href="#Executing-commands-from-or-diverting-output-to-a-file">Executing commands from or diverting output to a file</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-solve"><code>solve</code></a></td><td class="printindex-index-section"><a href="#Linear-equations-and-inversion">Linear equations and inversion</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-sort"><code>sort</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-source"><code>source</code></a></td><td class="printindex-index-section"><a href="#Executing-commands-from-or-diverting-output-to-a-file">Executing commands from or diverting output to a file</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-split"><code>split</code></a></td><td class="printindex-index-section"><a href="#Repetitive-execution">Repetitive execution</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-sqrt"><code>sqrt</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-stem"><code>stem</code></a></td><td class="printindex-index-section"><a href="#Examining-the-distribution-of-a-set-of-data">Examining the distribution of a set of data</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-step"><code>step</code></a></td><td class="printindex-index-section"><a href="#Generic-functions-for-extracting-model-information">Generic functions for extracting model information</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-step-1"><code>step</code></a></td><td class="printindex-index-section"><a href="#Updating-fitted-models">Updating fitted models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-sum"><code>sum</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-summary"><code>summary</code></a></td><td class="printindex-index-section"><a href="#Examining-the-distribution-of-a-set-of-data">Examining the distribution of a set of data</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-summary-1"><code>summary</code></a></td><td class="printindex-index-section"><a href="#Generic-functions-for-extracting-model-information">Generic functions for extracting model information</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-svd"><code>svd</code></a></td><td class="printindex-index-section"><a href="#Singular-value-decomposition-and-determinants">Singular value decomposition and determinants</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-T">T</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-T"><code>T</code></a></td><td class="printindex-index-section"><a href="#Logical-vectors">Logical vectors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-t"><code>t</code></a></td><td class="printindex-index-section"><a href="#Generalized-transpose-of-an-array">Generalized transpose of an array</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-t_002etest"><code>t.test</code></a></td><td class="printindex-index-section"><a href="#One_002d-and-two_002dsample-tests">One- and two-sample tests</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-table"><code>table</code></a></td><td class="printindex-index-section"><a href="#Index-matrices">Index matrices</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-table-1"><code>table</code></a></td><td class="printindex-index-section"><a href="#Frequency-tables-from-factors">Frequency tables from factors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-tan"><code>tan</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-tapply"><code>tapply</code></a></td><td class="printindex-index-section"><a href="#The-function-tapply_0028_0029-and-ragged-arrays">The function tapply() and ragged arrays</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-text"><code>text</code></a></td><td class="printindex-index-section"><a href="#Low_002dlevel-plotting-commands">Low-level plotting commands</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-title"><code>title</code></a></td><td class="printindex-index-section"><a href="#Low_002dlevel-plotting-commands">Low-level plotting commands</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-tree"><code>tree</code></a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-TRUE"><code>TRUE</code></a></td><td class="printindex-index-section"><a href="#Logical-vectors">Logical vectors</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-U">U</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-unclass"><code>unclass</code></a></td><td class="printindex-index-section"><a href="#The-class-of-an-object">The class of an object</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-update"><code>update</code></a></td><td class="printindex-index-section"><a href="#Updating-fitted-models">Updating fitted models</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-V">V</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-var"><code>var</code></a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-var-1"><code>var</code></a></td><td class="printindex-index-section"><a href="#The-function-tapply_0028_0029-and-ragged-arrays">The function tapply() and ragged arrays</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-var_002etest"><code>var.test</code></a></td><td class="printindex-index-section"><a href="#One_002d-and-two_002dsample-tests">One- and two-sample tests</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-vcov"><code>vcov</code></a></td><td class="printindex-index-section"><a href="#Generic-functions-for-extracting-model-information">Generic functions for extracting model information</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-vector"><code>vector</code></a></td><td class="printindex-index-section"><a href="#Vectors-and-assignment">Vectors and assignment</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-W">W</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-while"><code>while</code></a></td><td class="printindex-index-section"><a href="#Repetitive-execution">Repetitive execution</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-wilcox_002etest"><code>wilcox.test</code></a></td><td class="printindex-index-section"><a href="#One_002d-and-two_002dsample-tests">One- and two-sample tests</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-windows"><code>windows</code></a></td><td class="printindex-index-section"><a href="#Device-drivers">Device drivers</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Function-and-variable-index_vr_letter-X">X</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-X11"><code>X11</code></a></td><td class="printindex-index-section"><a href="#Device-drivers">Device drivers</a></td></tr> <tr><td colspan="3"><hr></td></tr> </table> <table summary="" class="vr-letters-footer-printindex"><tr><th>Jump to: </th><td><a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-1"><b>-</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-2"><b>:</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-3"><b>!</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-4"><b>?</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-5"><b>.</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-6"><b>*</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-7"><b>/</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-8"><b>&</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-9"><b>%</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-10"><b>^</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-11"><b>+</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-12"><b><</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-13"><b>=</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-14"><b>></b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-15"><b>|</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-16"><b>~</b></a> <br> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-A"><b>A</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-B"><b>B</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-C"><b>C</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-D"><b>D</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-E"><b>E</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-F"><b>F</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-G"><b>G</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-H"><b>H</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-I"><b>I</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-J"><b>J</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-K"><b>K</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-L"><b>L</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-M"><b>M</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-N"><b>N</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-O"><b>O</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-P"><b>P</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-Q"><b>Q</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-R"><b>R</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-S"><b>S</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-T"><b>T</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-U"><b>U</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-V"><b>V</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-W"><b>W</b></a> <a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-X"><b>X</b></a> </td></tr></table> </div> <hr> </div> <div class="appendix-level-extent" id="Concept-index"> <div class="nav-panel"> <p> Next: <a href="#References" accesskey="n" rel="next">References</a>, Previous: <a href="#Function-and-variable-index" accesskey="p" rel="prev">Function and variable index</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="appendix" id="Concept-index-1"><span>Appendix E Concept index<a class="copiable-link" href="#Concept-index-1"> ¶</a></span></h2> <div class="printindex cp-printindex"> <table summary="" class="cp-letters-header-printindex"><tr><th>Jump to: </th><td><a class="summary-letter-printindex" href="#Concept-index_cp_letter-A"><b>A</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-B"><b>B</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-C"><b>C</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-D"><b>D</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-E"><b>E</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-F"><b>F</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-G"><b>G</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-I"><b>I</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-K"><b>K</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-L"><b>L</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-M"><b>M</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-N"><b>N</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-O"><b>O</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-P"><b>P</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-Q"><b>Q</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-R"><b>R</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-S"><b>S</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-T"><b>T</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-U"><b>U</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-V"><b>V</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-W"><b>W</b></a> </td></tr></table> <table summary="" class="cp-entries-printindex" border="0"> <tr><td></td><th class="entries-header-printindex">Index Entry</th><th class="sections-header-printindex">Section</th></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-A">A</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Accessing-builtin-datasets">Accessing builtin datasets</a></td><td class="printindex-index-section"><a href="#Accessing-builtin-datasets">Accessing builtin datasets</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Additive-models">Additive models</a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Analysis-of-variance">Analysis of variance</a></td><td class="printindex-index-section"><a href="#Analysis-of-variance-and-model-comparison">Analysis of variance and model comparison</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Arithmetic-functions-and-operators">Arithmetic functions and operators</a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Arrays">Arrays</a></td><td class="printindex-index-section"><a href="#Arrays">Arrays</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Assignment">Assignment</a></td><td class="printindex-index-section"><a href="#Vectors-and-assignment">Vectors and assignment</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Attributes">Attributes</a></td><td class="printindex-index-section"><a href="#Objects">Objects</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-B">B</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Binary-operators">Binary operators</a></td><td class="printindex-index-section"><a href="#Defining-new-binary-operators">Defining new binary operators</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Box-plots">Box plots</a></td><td class="printindex-index-section"><a href="#One_002d-and-two_002dsample-tests">One- and two-sample tests</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-C">C</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Character-vectors">Character vectors</a></td><td class="printindex-index-section"><a href="#Character-vectors">Character vectors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Classes">Classes</a></td><td class="printindex-index-section"><a href="#The-class-of-an-object">The class of an object</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Classes-1">Classes</a></td><td class="printindex-index-section"><a href="#Object-orientation">Object orientation</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Concatenating-lists">Concatenating lists</a></td><td class="printindex-index-section"><a href="#Concatenating-lists">Concatenating lists</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Contrasts">Contrasts</a></td><td class="printindex-index-section"><a href="#Contrasts">Contrasts</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Control-statements">Control statements</a></td><td class="printindex-index-section"><a href="#Control-statements">Control statements</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-CRAN">CRAN</a></td><td class="printindex-index-section"><a href="#Contributed-packages-and-CRAN">Contributed packages and CRAN</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Customizing-the-environment">Customizing the environment</a></td><td class="printindex-index-section"><a href="#Customizing-the-environment">Customizing the environment</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-D">D</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Data-frames">Data frames</a></td><td class="printindex-index-section"><a href="#Data-frames">Data frames</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Default-values">Default values</a></td><td class="printindex-index-section"><a href="#Named-arguments-and-defaults">Named arguments and defaults</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Density-estimation">Density estimation</a></td><td class="printindex-index-section"><a href="#Examining-the-distribution-of-a-set-of-data">Examining the distribution of a set of data</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Determinants">Determinants</a></td><td class="printindex-index-section"><a href="#Singular-value-decomposition-and-determinants">Singular value decomposition and determinants</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Diverting-input-and-output">Diverting input and output</a></td><td class="printindex-index-section"><a href="#Executing-commands-from-or-diverting-output-to-a-file">Executing commands from or diverting output to a file</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Dynamic-graphics">Dynamic graphics</a></td><td class="printindex-index-section"><a href="#Dynamic-graphics">Dynamic graphics</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-E">E</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Eigenvalues-and-eigenvectors">Eigenvalues and eigenvectors</a></td><td class="printindex-index-section"><a href="#Eigenvalues-and-eigenvectors">Eigenvalues and eigenvectors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Empirical-CDFs">Empirical CDFs</a></td><td class="printindex-index-section"><a href="#Examining-the-distribution-of-a-set-of-data">Examining the distribution of a set of data</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-F">F</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Factors">Factors</a></td><td class="printindex-index-section"><a href="#Factors">Factors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Factors-1">Factors</a></td><td class="printindex-index-section"><a href="#Contrasts">Contrasts</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Families">Families</a></td><td class="printindex-index-section"><a href="#Families">Families</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Formulae">Formulae</a></td><td class="printindex-index-section"><a href="#Formulae-for-statistical-models">Formulae for statistical models</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-G">G</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Generalized-linear-models">Generalized linear models</a></td><td class="printindex-index-section"><a href="#Generalized-linear-models">Generalized linear models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Generalized-transpose-of-an-array">Generalized transpose of an array</a></td><td class="printindex-index-section"><a href="#Generalized-transpose-of-an-array">Generalized transpose of an array</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Generic-functions">Generic functions</a></td><td class="printindex-index-section"><a href="#Object-orientation">Object orientation</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Graphics-device-drivers">Graphics device drivers</a></td><td class="printindex-index-section"><a href="#Device-drivers">Device drivers</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Graphics-parameters">Graphics parameters</a></td><td class="printindex-index-section"><a href="#The-par_0028_0029-function">The par() function</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Grouped-expressions">Grouped expressions</a></td><td class="printindex-index-section"><a href="#Grouped-expressions">Grouped expressions</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-I">I</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Indexing-of-and-by-arrays">Indexing of and by arrays</a></td><td class="printindex-index-section"><a href="#Array-indexing">Array indexing</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Indexing-vectors">Indexing vectors</a></td><td class="printindex-index-section"><a href="#Index-vectors">Index vectors</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-K">K</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Kolmogorov_002dSmirnov-test">Kolmogorov-Smirnov test</a></td><td class="printindex-index-section"><a href="#Examining-the-distribution-of-a-set-of-data">Examining the distribution of a set of data</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-L">L</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Least-squares-fitting">Least squares fitting</a></td><td class="printindex-index-section"><a href="#Least-squares-fitting-and-the-QR-decomposition">Least squares fitting and the QR decomposition</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Linear-equations">Linear equations</a></td><td class="printindex-index-section"><a href="#Linear-equations-and-inversion">Linear equations and inversion</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Linear-models">Linear models</a></td><td class="printindex-index-section"><a href="#Linear-models">Linear models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Lists">Lists</a></td><td class="printindex-index-section"><a href="#Lists">Lists</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Local-approximating-regressions">Local approximating regressions</a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Loops-and-conditional-execution">Loops and conditional execution</a></td><td class="printindex-index-section"><a href="#Loops-and-conditional-execution">Loops and conditional execution</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-M">M</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Matrices">Matrices</a></td><td class="printindex-index-section"><a href="#Arrays">Arrays</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Matrix-multiplication">Matrix multiplication</a></td><td class="printindex-index-section"><a href="#Multiplication">Multiplication</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Maximum-likelihood">Maximum likelihood</a></td><td class="printindex-index-section"><a href="#Maximum-likelihood">Maximum likelihood</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Missing-values">Missing values</a></td><td class="printindex-index-section"><a href="#Missing-values">Missing values</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Mixed-models">Mixed models</a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-N">N</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Named-arguments">Named arguments</a></td><td class="printindex-index-section"><a href="#Named-arguments-and-defaults">Named arguments and defaults</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Namespace">Namespace</a></td><td class="printindex-index-section"><a href="#Namespaces">Namespaces</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Nonlinear-least-squares">Nonlinear least squares</a></td><td class="printindex-index-section"><a href="#Nonlinear-least-squares-and-maximum-likelihood-models">Nonlinear least squares and maximum likelihood models</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-O">O</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Object-orientation">Object orientation</a></td><td class="printindex-index-section"><a href="#Object-orientation">Object orientation</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Objects">Objects</a></td><td class="printindex-index-section"><a href="#Objects">Objects</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-One_002d-and-two_002dsample-tests">One- and two-sample tests</a></td><td class="printindex-index-section"><a href="#One_002d-and-two_002dsample-tests">One- and two-sample tests</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Ordered-factors">Ordered factors</a></td><td class="printindex-index-section"><a href="#Factors">Factors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Ordered-factors-1">Ordered factors</a></td><td class="printindex-index-section"><a href="#Contrasts">Contrasts</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Outer-products-of-arrays">Outer products of arrays</a></td><td class="printindex-index-section"><a href="#The-outer-product-of-two-arrays">The outer product of two arrays</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-P">P</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Packages">Packages</a></td><td class="printindex-index-section"><a href="#R-and-statistics">R and statistics</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Packages-1">Packages</a></td><td class="printindex-index-section"><a href="#Packages">Packages</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Probability-distributions">Probability distributions</a></td><td class="printindex-index-section"><a href="#Probability-distributions">Probability distributions</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-Q">Q</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-QR-decomposition">QR decomposition</a></td><td class="printindex-index-section"><a href="#Least-squares-fitting-and-the-QR-decomposition">Least squares fitting and the QR decomposition</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Quantile_002dquantile-plots">Quantile-quantile plots</a></td><td class="printindex-index-section"><a href="#Examining-the-distribution-of-a-set-of-data">Examining the distribution of a set of data</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-R">R</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Reading-data-from-files">Reading data from files</a></td><td class="printindex-index-section"><a href="#Reading-data-from-files">Reading data from files</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Recycling-rule">Recycling rule</a></td><td class="printindex-index-section"><a href="#Vector-arithmetic">Vector arithmetic</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Recycling-rule-1">Recycling rule</a></td><td class="printindex-index-section"><a href="#The-recycling-rule">The recycling rule</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Regular-sequences">Regular sequences</a></td><td class="printindex-index-section"><a href="#Generating-regular-sequences">Generating regular sequences</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Removing-objects">Removing objects</a></td><td class="printindex-index-section"><a href="#Data-permanency-and-removing-objects">Data permanency and removing objects</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Robust-regression">Robust regression</a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-S">S</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Scope">Scope</a></td><td class="printindex-index-section"><a href="#Scope">Scope</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Search-path">Search path</a></td><td class="printindex-index-section"><a href="#Managing-the-search-path">Managing the search path</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Shapiro_002dWilk-test">Shapiro-Wilk test</a></td><td class="printindex-index-section"><a href="#Examining-the-distribution-of-a-set-of-data">Examining the distribution of a set of data</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Singular-value-decomposition">Singular value decomposition</a></td><td class="printindex-index-section"><a href="#Singular-value-decomposition-and-determinants">Singular value decomposition and determinants</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Statistical-models">Statistical models</a></td><td class="printindex-index-section"><a href="#Statistical-models-in-R">Statistical models in R</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Student_0027s-t-test">Student’s <em class="math">t</em> test</a></td><td class="printindex-index-section"><a href="#One_002d-and-two_002dsample-tests">One- and two-sample tests</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-T">T</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Tabulation">Tabulation</a></td><td class="printindex-index-section"><a href="#Frequency-tables-from-factors">Frequency tables from factors</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Tree_002dbased-models">Tree-based models</a></td><td class="printindex-index-section"><a href="#Some-non_002dstandard-models">Some non-standard models</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-U">U</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Updating-fitted-models">Updating fitted models</a></td><td class="printindex-index-section"><a href="#Updating-fitted-models">Updating fitted models</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-V">V</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Vectors">Vectors</a></td><td class="printindex-index-section"><a href="#Simple-manipulations-numbers-and-vectors">Simple manipulations numbers and vectors</a></td></tr> <tr><td colspan="3"><hr></td></tr> <tr><th id="Concept-index_cp_letter-W">W</th></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Wilcoxon-test">Wilcoxon test</a></td><td class="printindex-index-section"><a href="#One_002d-and-two_002dsample-tests">One- and two-sample tests</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Workspace">Workspace</a></td><td class="printindex-index-section"><a href="#Data-permanency-and-removing-objects">Data permanency and removing objects</a></td></tr> <tr><td></td><td class="printindex-index-entry"><a href="#index-Writing-functions">Writing functions</a></td><td class="printindex-index-section"><a href="#Writing-your-own-functions">Writing your own functions</a></td></tr> <tr><td colspan="3"><hr></td></tr> </table> <table summary="" class="cp-letters-footer-printindex"><tr><th>Jump to: </th><td><a class="summary-letter-printindex" href="#Concept-index_cp_letter-A"><b>A</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-B"><b>B</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-C"><b>C</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-D"><b>D</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-E"><b>E</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-F"><b>F</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-G"><b>G</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-I"><b>I</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-K"><b>K</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-L"><b>L</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-M"><b>M</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-N"><b>N</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-O"><b>O</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-P"><b>P</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-Q"><b>Q</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-R"><b>R</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-S"><b>S</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-T"><b>T</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-U"><b>U</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-V"><b>V</b></a> <a class="summary-letter-printindex" href="#Concept-index_cp_letter-W"><b>W</b></a> </td></tr></table> </div> <hr> </div> <div class="appendix-level-extent" id="References"> <div class="nav-panel"> <p> Previous: <a href="#Concept-index" accesskey="p" rel="prev">Concept index</a>, Up: <a href="#Top" accesskey="u" rel="up">An Introduction to R</a> [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p> </div> <h2 class="appendix" id="References-1"><span>Appendix F References<a class="copiable-link" href="#References-1"> ¶</a></span></h2> <p>D. M. Bates and D. G. Watts (1988), <em class="emph">Nonlinear Regression Analysis and Its Applications.</em> John Wiley & Sons, New York. </p> <p>Richard A. Becker, John M. Chambers and Allan R. Wilks (1988), <em class="emph">The New S Language.</em> Chapman & Hall, New York. This book is often called the “<em class="emph">Blue Book</em>”. </p> <p>John M. Chambers and Trevor J. Hastie eds. (1992), <em class="emph">Statistical Models in S.</em> Chapman & Hall, New York. This is also called the “<em class="emph">White Book</em>”. </p> <p>John M. Chambers (1998) <em class="emph">Programming with Data</em>. Springer, New York. This is also called the “<em class="emph">Green Book</em>”. </p> <p>A. C. Davison and D. V. Hinkley (1997), <em class="emph">Bootstrap Methods and Their Applications</em>, Cambridge University Press. </p> <p>Annette J. Dobson (1990), <em class="emph">An Introduction to Generalized Linear Models</em>, Chapman and Hall, London. </p> <p>Peter McCullagh and John A. Nelder (1989), <em class="emph">Generalized Linear Models.</em> Second edition, Chapman and Hall, London. </p> <p>John A. Rice (1995), <em class="emph">Mathematical Statistics and Data Analysis.</em> Second edition. Duxbury Press, Belmont, CA. </p> <p>S. D. Silvey (1970), <em class="emph">Statistical Inference.</em> Penguin, London. </p> </div> </div> <div class="footnotes-segment"> <hr> <h4 class="footnotes-heading">Footnotes</h4> <h5 class="footnote-body-heading"><a id="FOOT1" href="#DOCF1">(1)</a></h5> <p>ACM Software Systems award, 1998: <a class="uref" href="https://awards.acm.org/award_winners/chambers_6640862.cfm">https://awards.acm.org/award_winners/chambers_6640862.cfm</a>.</p> <h5 class="footnote-body-heading"><a id="FOOT2" href="#DOCF2">(2)</a></h5> <p>For portable R code (including that to be used in R packages) only A–Z, a–z, and 0–9 should be used.</p> <h5 class="footnote-body-heading"><a id="FOOT3" href="#DOCF3">(3)</a></h5> <p><strong class="strong">not</strong> inside strings, nor within the argument list of a function definition</p> <h5 class="footnote-body-heading"><a id="FOOT4" href="#DOCF4">(4)</a></h5> <p>some of the consoles will not allow you to enter more, and amongst those which do some will silently discard the excess and some will use it as the start of the next line.</p> <h5 class="footnote-body-heading"><a id="FOOT5" href="#DOCF5">(5)</a></h5> <p>of unlimited length.</p> <h5 class="footnote-body-heading"><a id="FOOT6" href="#DOCF6">(6)</a></h5> <p>The leading “dot” in this file name makes it <em class="emph">invisible</em> in normal file listings in UNIX, and in default GUI file listings on macOS and Windows.</p> <h5 class="footnote-body-heading"><a id="FOOT7" href="#DOCF7">(7)</a></h5> <p>With other than vector types of argument, such as <code class="code">list</code> mode arguments, the action of <code class="code">c()</code> is rather different. See <a class="ref" href="#Concatenating-lists">Concatenating lists</a>.</p> <h5 class="footnote-body-heading"><a id="FOOT8" href="#DOCF8">(8)</a></h5> <p>Actually, it is still available as <code class="code">.Last.value</code> before any other statements are executed.</p> <h5 class="footnote-body-heading"><a id="FOOT9" href="#DOCF9">(9)</a></h5> <p><code class="code">paste(..., collapse=<var class="var">ss</var>)</code> joins the arguments into a single character string putting <var class="var">ss</var> in between, e.g., <code class="code">ss <- "|"</code>. There are more tools for character manipulation, see the help for <code class="code">sub</code> and <code class="code">substring</code>.</p> <h5 class="footnote-body-heading"><a id="FOOT10" href="#DOCF10">(10)</a></h5> <p><em class="emph">numeric</em> mode is actually an amalgam of two distinct modes, namely <em class="emph">integer</em> and <em class="emph">double</em> precision, as explained in the manual.</p> <h5 class="footnote-body-heading"><a id="FOOT11" href="#DOCF11">(11)</a></h5> <p>Note however that <code class="code">length(<var class="var">object</var>)</code> does not always contain intrinsic useful information, e.g., when <code class="code"><var class="var">object</var></code> is a function.</p> <h5 class="footnote-body-heading"><a id="FOOT12" href="#DOCF12">(12)</a></h5> <p>In general, coercion from numeric to character and back again will not be exactly reversible, because of roundoff errors in the character representation.</p> <h5 class="footnote-body-heading"><a id="FOOT13" href="#DOCF13">(13)</a></h5> <p>A different style using ‘formal’ or ‘S4’ classes is provided in package <code class="code">methods</code>.</p> <h5 class="footnote-body-heading"><a id="FOOT14" href="#DOCF14">(14)</a></h5> <p>Readers should note that there are eight states and territories in Australia, namely the Australian Capital Territory, New South Wales, the Northern Territory, Queensland, South Australia, Tasmania, Victoria and Western Australia.</p> <h5 class="footnote-body-heading"><a id="FOOT15" href="#DOCF15">(15)</a></h5> <p>Note that <code class="code">tapply()</code> also works in this case when its second argument is not a factor, e.g., ‘<samp class="samp"><code class="code">tapply(incomes, state)</code></samp>’, and this is true for quite a few other functions, since arguments are <em class="emph">coerced</em> to factors when necessary (using <code class="code">as.factor()</code>).</p> <h5 class="footnote-body-heading"><a id="FOOT16" href="#DOCF16">(16)</a></h5> <p>Note that <code class="code">x %*% x</code> is ambiguous, as it could mean either x’x or x x’, where x is the column form. In such cases the smaller matrix seems implicitly to be the interpretation adopted, so the scalar x’x is in this case the result. The matrix x x’ may be calculated either by <code class="code">cbind(x) %*% x</code> or <code class="code">x %*% rbind(x)</code> since the result of <code class="code">rbind()</code> or <code class="code">cbind()</code> is always a matrix. However, the best way to compute x’x or x x’ is <code class="code">crossprod(x)</code> or <code class="code">x %o% x</code> respectively.</p> <h5 class="footnote-body-heading"><a id="FOOT17" href="#DOCF17">(17)</a></h5> <p>Even better would be to form a matrix square root B with A = BB’ and find the squared length of the solution of By = x , perhaps using the Cholesky or eigendecomposition of A. </p> <h5 class="footnote-body-heading"><a id="FOOT18" href="#DOCF18">(18)</a></h5> <p>See the on-line help for <code class="code">autoload</code> for the meaning of the second term.</p> <h5 class="footnote-body-heading"><a id="FOOT19" href="#DOCF19">(19)</a></h5> <p>Under UNIX, the utilities <code class="command">sed</code> or <code class="command">awk</code> can be used.</p> <h5 class="footnote-body-heading"><a id="FOOT20" href="#DOCF20">(20)</a></h5> <p>to be discussed later, or use <code class="code">xyplot</code> from package <a class="url" href="https://CRAN.R-project.org/package=lattice"><strong class="strong">lattice</strong></a>.</p> <h5 class="footnote-body-heading"><a id="FOOT21" href="#DOCF21">(21)</a></h5> <p>See also the methods described in <a class="ref" href="#Statistical-models-in-R">Statistical models in R</a></p> <h5 class="footnote-body-heading"><a id="FOOT22" href="#DOCF22">(22)</a></h5> <p>In some sense this mimics the behavior in <small class="sc">S-PLUS</small> since in <small class="sc">S-PLUS</small> this operator always creates or assigns to a global variable.</p> <h5 class="footnote-body-heading"><a id="FOOT23" href="#DOCF23">(23)</a></h5> <p>So it is hidden under UNIX.</p> <h5 class="footnote-body-heading"><a id="FOOT24" href="#DOCF24">(24)</a></h5> <p>Some graphics parameters such as the size of the current device are for information only.</p> <h5 class="footnote-body-heading"><a id="FOOT25" href="#DOCF25">(25)</a></h5> <p>The ‘Emacs Speaks Statistics’ package; see the <abbr class="acronym">URL</abbr> <a class="uref" href="https://ESS.R-project.org/">https://ESS.R-project.org/</a></p> <h5 class="footnote-body-heading"><a id="FOOT26" href="#DOCF26">(26)</a></h5> <p>It is possible to build R using an emulation of GNU <strong class="strong">readline</strong>, such as one based on NetBSD’s editline (also known as libedit), in which case only a subset of the capabilities may be provided.</p> <h5 class="footnote-body-heading"><a id="FOOT27" href="#DOCF27">(27)</a></h5> <p>On a PC keyboard this is usually the Alt key, occasionally the ‘Windows’ key. On a Mac keyboard normally no meta key is available.</p> <h5 class="footnote-body-heading"><a id="FOOT28" href="#DOCF28">(28)</a></h5> <p>In particular, not versions 6.3 or later: this is worked around as from R 3.4.0.</p> </div> </body> </html>