Log In
Or create an account ->
Imperial Library
Home
About
News
Upload
Forum
Help
Login/SignUp
Index
Art of R Programming
Acknowledgments
Introduction
Why Use R for Your Statistical Work?
Object-Oriented Programming
Functional Programming
Whom Is This Book For?
My Own Background
1. Getting Started
How to Run R
Interactive Mode
Batch Mode
A First R Session
Introduction to Functions
Variable Scope
Default Arguments
Preview of Some Important R Data Structures
Vectors, the R Workhorse
Scalars
Character Strings
Matrices
Lists
Data Frames
Classes
Extended Example: Regression Analysis of Exam Grades
Startup and Shutdown
Getting Help
The help() Function
The example() Function
If You Don’t Know Quite What You’re Looking For
Help for Other Topics
Help for Batch Mode
Help on the Internet
2. Vectors
Scalars, Vectors, Arrays, and Matrices
Adding and Deleting Vector Elements
Obtaining the Length of a Vector
Matrices and Arrays as Vectors
Declarations
Recycling
Common Vector Operations
Vector Arithmetic and Logical Operations
Vector Indexing
Generating Useful Vectors with the : Operator
Generating Vector Sequences with seq()
Repeating Vector Constants with rep()
Using all() and any()
Extended Example: Finding Runs of Consecutive Ones
Extended Example: Predicting Discrete-Valued Time Series
Vectorized Operations
Vector In, Vector Out
Vector In, Matrix Out
NA and NULL Values
Using NA
Using NULL
Filtering
Generating Filtering Indices
Filtering with the subset() Function
The Selection Function which()
A Vectorized if-then-else: The ifelse() Function
Extended Example: A Measure of Association
Extended Example: Recoding an Abalone Data Set
Testing Vector Equality
Vector Element Names
More on c()
3. Matrices and Arrays
Creating Matrices
General Matrix Operations
Performing Linear Algebra Operations on Matrices
Matrix Indexing
Extended Example: Image Manipulation
Filtering on Matrices
Extended Example: Generating a Covariance Matrix
Applying Functions to Matrix Rows and Columns
Using the apply() Function
Extended Example: Finding Outliers
Adding and Deleting Matrix Rows and Columns
Changing the Size of a Matrix
Extended Example: Finding the Closest Pair of Vertices in a Graph
More on the Vector/Matrix Distinction
Avoiding Unintended Dimension Reduction
Naming Matrix Rows and Columns
Higher-Dimensional Arrays
4. Lists
Creating Lists
General List Operations
List Indexing
Adding and Deleting List Elements
Getting the Size of a List
Extended Example: Text Concordance
Accessing List Components and Values
Applying Functions to Lists
Using the lapply() and sapply() Functions
Extended Example: Text Concordance, Continued
Extended Example: Back to the Abalone Data
Recursive Lists
5. Data Frames
Creating Data Frames
Accessing Data Frames
Extended Example: Regression Analysis of Exam Grades Continued
Other Matrix-Like Operations
Extracting Subdata Frames
More on Treatment of NA Values
Using the rbind() and cbind() Functions and Alternatives
Applying apply()
Extended Example: A Salary Study
Merging Data Frames
Extended Example: An Employee Database
Applying Functions to Data Frames
Using lapply() and sapply() on Data Frames
Extended Example: Applying Logistic Regression Models
Extended Example: Aids for Learning Chinese Dialects
6. Factors and Tables
Factors and Levels
Common Functions Used with Factors
The tapply() Function
The split() Function
The by() Function
Working with Tables
Matrix/Array-Like Operations on Tables
Extended Example: Extracting a Subtable
Extended Example: Finding the Largest Cells in a Table
Other Factor- and Table-Related Functions
The aggregate() Function
The cut() Function
7. R Programming Structures
Control Statements
Loops
Looping Over Nonvector Sets
if-else
Arithmetic and Boolean Operators and Values
Default Values for Arguments
Return Values
Deciding Whether to Explicitly Call return()
Returning Complex Objects
Functions Are Objects
Environment and Scope Issues
The Top-Level Environment
The Scope Hierarchy
More on ls()
Functions Have (Almost) No Side Effects
Extended Example: A Function to Display the Contents of a Call Frame
No Pointers in R
Writing Upstairs
Writing to Nonlocals with the Superassignment Operator
Writing to Nonlocals with assign()
Extended Example: Discrete-Event Simulation in R
When Should You Use Global Variables?
Closures
Recursion
A Quicksort Implementation
Extended Example: A Binary Search Tree
Replacement Functions
What’s Considered a Replacement Function?
Extended Example: A Self-Bookkeeping Vector Class
Tools for Composing Function Code
Text Editors and Integrated Development Environments
The edit() Function
Writing Your Own Binary Operations
Anonymous Functions
8. Doing Math and Simulations in R
Math Functions
Extended Example: Calculating a Probability
Cumulative Sums and Products
Minima and Maxima
Calculus
Functions for Statistical Distributions
Sorting
Linear Algebra Operations on Vectors and Matrices
Extended Example: Vector Cross Product
Extended Example: Finding Stationary Distributions of Markovv Chains
Set Operations
Simulation Programming in R
Built-In Random Variate Generators
Obtaining the Same Random Stream in Repeated Runs
Extended Example: A Combinatorial Simulation
9. Object-Oriented Programming
S3 Classes
S3 Generic Functions
Example: OOP in the lm() Linear Model Function
Finding the Implementations of Generic Methods
Writing S3 Classes
Using Inheritance
Extended Example: A Class for Storing Upper-Triangular Matrices
Extended Example: A Procedure for Polynomial Regression
S4 Classes
Writing S4 Classes
Implementing a Generic Function on an S4 Class
S3 Versus S4
Managing Your Objects
Listing Your Objects with the ls() Function
Removing Specific Objects with the rm() Function
Saving a Collection of Objects with the save() Function
“What Is This?”
The exists() Function
10. Input/Output
Accessing the Keyboard and Monitor
Using the scan() Function
Using the readline() Function
Printing to the Screen
Reading and Writing Files
Reading a Data Frame or Matrix from a File
Reading Text Files
Introduction to Connections
Extended Example: Reading PUMS Census Files
Accessing Files on Remote Machines via URLs
Writing to a File
Getting File and Directory Information
Extended Example: Sum the Contents of Many Files
Accessing the Internet
Overview of TCP/IP
Sockets in R
Extended Example: Implementing Parallel R
11. String Manipulation
An Overview of String-Manipulation Functions
grep()
nchar()
paste()
sprintf()
substr()
strsplit()
regexpr()
gregexpr()
Regular Expressions
Extended Example: Testing a Filename for a Given Suffix
Extended Example: Forming Filenames
Use of String Utilities in the edtdbg Debugging Tool
12. Graphics
Creating Graphs
The Workhorse of R Base Graphics: The plot() Function
Adding Lines: The abline() Function
Starting a New Graph While Keeping the Old Ones
Extended Example: Two Density Estimates on the Same Graph
Extended Example: More on the Polynomial Regression Example
Adding Points: The points() Function
Adding a Legend: The legend() Function
Adding Text: The text() Function
Pinpointing Locations: The locator() Function
Restoring a Plot
Customizing Graphs
Changing Character Sizes: The cex Option
Changing the Range of Axes: The xlim and ylim Options
Adding a Polygon: The polygon() Function
Smoothing Points: The lowess() and loess() Functions
Graphing Explicit Functions
Extended Example: Magnifying a Portion of a Curve
Saving Graphs to Files
R Graphics Devices
Saving the Displayed Graph
Closing an R Graphics Device
Creating Three-Dimensional Plots
13. Debugging
Fundamental Principles of Debugging
The Essence of Debugging: The Principle of Confirmation
Start Small
Debug in a Modular, Top-Down Manner
Antibugging
Why Use a Debugging Tool?
Using R Debugging Facilities
Single-Stepping with the debug() and browser() Functions
Using Browser Commands
Setting Breakpoints
Calling browser() Directly
Using the setBreakpoint() Function
Tracking with the trace() Function
Performing Checks After a Crash with the traceback() and debugger() Function
Extended Example: Two Full Debugging Sessions
Debugging Finding Runs of Ones
Debugging Finding City Pairs
Moving Up in the World: More Convenient Debugging Tools
Ensuring Consistency in Debugging Simulation Code
Syntax and Runtime Errors
Running GDB on R Itself
14. Performance Enhancement: Speed and Memory
Writing Fast R Code
The Dreaded for Loop
Vectorization for Speedup
Extended Example: Achieving Better Speed in a Monte Carlo Simulation
Extended Example: Generating a Powers Matrix
Functional Programming and Memory Issues
Vector Assignment Issues
Copy-on-Change Issues
Extended Example: Avoiding Memory Copy
Using Rprof() to Find Slow Spots in Your Code
Monitoring with Rprof()
How Rprof() Works
Byte Code Compilation
Oh No, the Data Doesn’t Fit into Memory!
Chunking
Using R Packages for Memory Management
15. Interfacing R to Other Languages
Writing C/C++ Functions to Be Called from R
Some R-to-C/C++ Preliminaries
Example: Extracting Subdiagonals from a Square Matrix
Compiling and Running Code
Debugging R/C Code
Extended Example: Prediction of Discrete-Valued Time Series
Using R from Python
Installing RPy
RPy Syntax
16. Parallel R
The Mutual Outlinks Problem
Introducing the snow Package
Running snow Code
Analyzing the snow Code
How Much Speedup Can Be Attained?
Extended Example: K-Means Clustering
Resorting to C
Using Multicore Machines
Extended Example: Mutual Outlinks Problem in OpenMP
Running the OpenMP Code
OpenMP Code Analysis
Other OpenMP Pragmas
The omp barrier Pragma
The omp critical Pragma
The omp single Pragma
GPU Programming
General Performance Considerations
Sources of Overhead
Shared-Memory Machines
Networked Systems of Computers
Embarrassingly Parallel Applications and Those That Aren’t
Static Versus Dynamic Task Assignment
Software Alchemy: Turning General Problems into Embarrassingly Parallel Ones
Debugging Parallel R Code
A. Installing R
Downloading R from CRAN
Installing from a Linux Package Manager
Installing from Source
B. Installing and Using Packages
Package Basics
Loading a Package from Your Hard Drive
Downloading a Package from the Web
Installing Packages Automatically
Installing Packages Manually
Listing the Functions in a Package
Index
About the Author
Colophon
← Prev
Back
Next →
← Prev
Back
Next →