The R Base Package

The R Base Package [R logo]

Help pages for package `base' version 2.4.1

A B C D E F G H I J K L M N O P Q R S T U V W X Z misc

-- --

base-package The R Base Package

-- --

! | Logical Operators
!= | Relational Operators
" | Quotes
$ | Extract or Replace Parts of an Object
$.DLLInfo | Get DLLs Loaded in Current Session
$.package_version | Package versions
%% | Arithmetic Operators
%*% | Matrix Multiplication
%/% | Arithmetic Operators
%in% | Value Matching
%o% | Outer Product of Arrays
%x% | Kronecker products on arrays
& | Logical Operators
&& | Logical Operators
' | Quotes
( | Parentheses and Braces
* | Arithmetic Operators
*.difftime | Time Intervals
+ | Arithmetic Operators
+.Date | Operators on the Date Class
+.POSIXt | Date-Time Classes
- | Arithmetic Operators
-.Date | Operators on the Date Class
-.POSIXt | Date-Time Classes
-> | Assignment Operators
->> | Assignment Operators
.Autoloaded | On-demand Loading of Packages
.AutoloadEnv | On-demand Loading of Packages
.BaseNamespaceEnv | Environment Access
.C | Foreign Function Interface
.Call | Foreign Function Interface
.Class | Class Methods
.decode_package_version | Package versions
.Defunct | Marking Objects as Defunct
.deparseOpts | Options for Expression Deparsing
.Deprecated | Marking Objects as Deprecated
.Device | Lists of Open Graphics Devices
.Devices | Lists of Open Graphics Devices
.dynLibs | Loading Shared Libraries
.encode_package_version | Package versions
.External | Foreign Function Interface
.First | Initialization at Start of an R Session
.First.lib | Loading and Listing of Packages
.First.sys | Initialization at Start of an R Session
.Fortran | Foreign Function Interface
.Generic | Class Methods
.GlobalEnv | Environment Access
.Group | S3 Group Generic Functions
.handleSimpleError | Condition Handling and Recovery
.Internal | Call an Internal Function
.Last | Terminate an R Session
.Last.lib | Loading and Listing of Packages
.Last.value | Value of Last Evaluated Expression
.leap.seconds | Date-Time Classes
.libPaths | Search Paths for Packages
.Library | Search Paths for Packages
.Machine | Numerical Characteristics of the Machine
.Method | Class Methods
.noGenerics | Loading and Listing of Packages
.NotYetImplemented | Not Yet Implemented Functions and Unused Arguments
.NotYetUsed | Not Yet Implemented Functions and Unused Arguments
.onAttach | Hooks for Name Space events
.onLoad | Hooks for Name Space events
.onUnload | Hooks for Name Space events
.Options | Options Settings
.OptRequireMethods | Initialization at Start of an R Session
.packages | Listing of Packages
.Platform | Platform Specific Variables
.Primitive | Call a ``Primitive'' Internal Function
.primTrace | Interactive Tracing and Debugging of Calls to a Function or Method
.primUntrace | Interactive Tracing and Debugging of Calls to a Function or Method
.Random.seed | Random Number Generation
.Renviron | Initialization at Start of an R Session
.Rprofile | Initialization at Start of an R Session
.Script | Scripting Language Interface
.signalSimpleWarning | Condition Handling and Recovery
.standard_regexps | Miscellaneous Internal/Programming Utilities
.Traceback | Print Call Stacks
.userHooksEnv | Functions to Get and Set Hooks for Load, Attach, Detach and Unload
.__H__.cbind | Combine R Objects by Rows or Columns
.__H__.rbind | Combine R Objects by Rows or Columns
/ | Arithmetic Operators
/.difftime | Time Intervals
: | Colon Operator
:: | Double Colon and Triple Colon Operators
::: | Double Colon and Triple Colon Operators
< | Relational Operators
<= | Relational Operators
= | Assignment Operators
== | Relational Operators
> | Relational Operators
>= | Relational Operators
@ | Extract Slots

-- A --

abbreviate | Abbreviate Strings
abs | Miscellaneous Mathematical Functions
acos | Trigonometric Functions
acosh | Hyperbolic Functions
addTaskCallback | Add or remove a top-level task callback
agrep | Approximate String Matching (Fuzzy Matching)
alist | Lists - Generic and Dotted Pairs
all | Are All Values True?
all.equal | Test if Two Objects are (Nearly) Equal
all.equal.POSIXct | Date-Time Classes
all.names | Find All Names in an Expression
all.vars | Find All Names in an Expression
any | Are Some Values True?
aperm | Array Transposition
append | Vector Merging
apply | Apply Functions Over Array Margins
Arg | Complex Vectors
args | Argument List of a Function
Arithmetic | Arithmetic Operators
array | Multi-way Arrays
as.array | Multi-way Arrays
as.call | Function Calls
as.character | Character Vectors
as.character.condition | Condition Handling and Recovery
as.character.Date | Date Conversion Functions to and from Character
as.character.default | Character Vectors
as.character.error | Condition Handling and Recovery
as.character.factor | Character Vectors
as.character.hexmode | Display Numbers in Hexadecimal
as.character.octmode | Display Numbers in Octal
as.character.package_version | Package versions
as.character.POSIXt | Date-time Conversion Functions to and from Character
as.complex | Complex Vectors
as.data.frame | Coerce to a Data Frame
as.data.frame.Date | Date Class
as.data.frame.default | Coerce to a Data Frame
as.data.frame.factor | Coerce to a Data Frame
as.data.frame.integer | Coerce to a Data Frame
as.data.frame.list | Coerce to a Data Frame
as.data.frame.logical | Coerce to a Data Frame
as.data.frame.matrix | Coerce to a Data Frame
as.data.frame.model.matrix | Coerce to a Data Frame
as.data.frame.numeric | Coerce to a Data Frame
as.data.frame.ordered | Coerce to a Data Frame
as.data.frame.package_version | Package versions
as.data.frame.POSIXct | Date-Time Classes
as.data.frame.POSIXlt | Date-Time Classes
as.data.frame.raw | Coerce to a Data Frame
as.data.frame.table | Cross Tabulation and Table Creation
as.data.frame.ts | Coerce to a Data Frame
as.data.frame.vector | Coerce to a Data Frame
as.Date | Date Conversion Functions to and from Character
as.difftime | Time Intervals
as.double | Double Precision Vectors
as.environment | Coerce to an Environment Object
as.expression | Unevaluated Expressions
as.factor | Factors
as.function | Convert Object to Function
as.integer | Integer Vectors
as.list | Lists - Generic and Dotted Pairs
as.logical | Logical Vectors
as.matrix | Matrices
as.matrix.noquote | Class for ``no quote'' Printing of Character Strings
as.matrix.POSIXlt | Date-Time Classes
as.name | Names and Symbols
as.null | The Null Object
as.numeric | Numeric Vectors
as.numeric.POSIXlt | Date-time Conversion Functions
as.ordered | Factors
as.package_version | Package versions
as.pairlist | Lists - Generic and Dotted Pairs
as.POSIXct | Date-time Conversion Functions
as.POSIXlt | Date-time Conversion Functions
as.qr | The QR Decomposition of a Matrix
as.raw | Raw Vectors
as.real | Real Vectors
as.single | Double Precision Vectors
as.symbol | Names and Symbols
as.table | Cross Tabulation and Table Creation
as.vector | Vectors
asin | Trigonometric Functions
asinh | Hyperbolic Functions
AsIs | Inhibit Interpretation/Conversion of Objects
asS4 | Test for an S4 object
assign | Assign a Value to a Name
atan | Trigonometric Functions
atan2 | Trigonometric Functions
atanh | Hyperbolic Functions
attach | Attach Set of R Objects to Search Path
attachNamespace | Loading and Unloading Name Spaces
attr | Object Attributes
attr.all.equal | Test if Two Objects are (Nearly) Equal
attributes | Object Attribute Lists
autoload | On-demand Loading of Packages
autoloader | On-demand Loading of Packages
Autoloads | On-demand Loading of Packages

-- B --

backquote | Quotes
backsolve | Solve an Upper or Lower Triangular System
backtick | Quotes
base | The R Base Package
base-deprecated | Deprecated Functions in Base package
baseenv | Environment Access
basename | Manipulate File Paths
Bessel | Bessel Functions
bessel | Bessel Functions
besselI | Bessel Functions
besselJ | Bessel Functions
besselK | Bessel Functions
besselY | Bessel Functions
beta | Special Functions of Mathematics
bindtextdomain | Translate Text Messages
body | Access to and Manipulation of the Body of a Function
bquote | Partial substitution in expressions
break | Control Flow
browser | Environment Browser
builtins | Returns the Names of All Built-in Objects
by | Apply a Function to a Data Frame split by Factors
bzfile | Functions to Manipulate Connections

-- C --

c | Combine Values into a Vector or List
c.Date | Date Class
c.noquote | Class for ``no quote'' Printing of Character Strings
c.package_version | Package versions
c.POSIXct | Date-Time Classes
c.POSIXlt | Date-Time Classes
call | Function Calls
capabilities | Report Capabilities of this Build of R
casefold | Character Translation and Casefolding
cat | Concatenate and Print
cbind | Combine R Objects by Rows or Columns
ceiling | Rounding of Numbers
char.expand | Expand a String with Respect to a Target Table
character | Character Vectors
charmatch | Partial String Matching
charToRaw | Convert to or from Raw Vectors
chartr | Character Translation and Casefolding
check_tzones | Date-Time Classes
chol | The Choleski Decomposition
chol2inv | Inverse from Choleski Decomposition
choose | Special Functions of Mathematics
class | Object Classes
clipboard | Functions to Manipulate Connections
close | Functions to Manipulate Connections
closeAllConnections | Display Connections
col | Column Indexes
colMeans | Form Row and Column Sums and Means
colnames | Row and Column Names
colSums | Form Row and Column Sums and Means
commandArgs | Extract Command Line Arguments
comment | Query or Set a `Comment' Attribute
Comparison | Relational Operators
Complex | S3 Group Generic Functions
complex | Complex Vectors
computeRestarts | Condition Handling and Recovery
condition | Condition Handling and Recovery
conditionCall | Condition Handling and Recovery
conditionMessage | Condition Handling and Recovery
conditions | Condition Handling and Recovery
conflicts | Search for Masked Objects on the Search Path
Conj | Complex Vectors
connection | Functions to Manipulate Connections
connections | Functions to Manipulate Connections
contributors | R Project Contributors
Control | Control Flow
copyright | Copyrights of Files Used to Build R
copyrights | Copyrights of Files Used to Build R
cos | Trigonometric Functions
cosh | Hyperbolic Functions
count.fields | Count the Number of Fields per Line
crossprod | Matrix Crossproduct
Cstack_info | Report Information on C Stack Size and Usage
cummax | Cumulative Sums, Products, and Extremes
cummin | Cumulative Sums, Products, and Extremes
cumprod | Cumulative Sums, Products, and Extremes
cumsum | Cumulative Sums, Products, and Extremes
cut | Convert Numeric to Factor
cut.Date | Convert a Date or Date-Time Object to a Factor
cut.default | Convert Numeric to Factor
cut.POSIXt | Convert a Date or Date-Time Object to a Factor

-- D --

data.class | Object Classes
data.frame | Data Frames
data.matrix | Data Frame to Numeric Matrix
Date | Date Class
date | System Date and Time
Dates | Date Class
DateTimeClasses | Date-Time Classes
debug | Debug a Function
default.stringsAsFactors | Data Frames
Defunct | Marking Objects as Defunct
delayedAssign | Delay Evaluation
deparse | Expression Deparsing
Deprecated | Marking Objects as Deprecated
det | Calculate the Determinant of a Matrix
detach | Detach Objects from the Search Path
determinant | Calculate the Determinant of a Matrix
dget | Write an Internal Object to a File
diag | Matrix Diagonals
diff | Lagged Differences
difftime | Time Intervals
digamma | Special Functions of Mathematics
dim | Dimensions of an Object
dimnames | Dimnames of an Object
dir | List the Files in a Directory/Folder
dir.create | File and Directory Manipulation
dirname | Manipulate File Paths
do.call | Execute a Function Call
double | Double Precision Vectors
dput | Write an Internal Object to a File
dQuote | Quote Text
drop | Drop Redundant Extent Information
dump | Text Representations of R Objects
duplicated | Determine Duplicate Elements
duplicated.POSIXlt | Date-Time Classes
dyn.load | Foreign Function Interface
dyn.unload | Foreign Function Interface

-- E --

eapply | Apply a Function over values in an environment
eigen | Spectral Decomposition of a Matrix
else | Control Flow
emptyenv | Environment Access
encodeString | Encode Character Vector as for Printing
environment | Environment Access
eval | Evaluate an (Unevaluated) Expression
evalq | Evaluate an (Unevaluated) Expression
exists | Is an Object Defined?
exp | Logarithms and Exponentials
expand.grid | Create a Data Frame from All Combinations of Factors
expm1 | Logarithms and Exponentials
expression | Unevaluated Expressions
Extract | Extract or Replace Parts of an Object

-- F --

F | Logical Vectors
factor | Factors
factorial | Special Functions of Mathematics
FALSE | Logical Vectors
fifo | Functions to Manipulate Connections
file | Functions to Manipulate Connections
file.access | Ascertain File Accessibility
file.append | File and Directory Manipulation
file.choose | Choose a File Interactively
file.copy | File and Directory Manipulation
file.create | File and Directory Manipulation
file.exists | File and Directory Manipulation
file.info | Extract File Information
file.path | Construct Path to File
file.remove | File and Directory Manipulation
file.rename | File and Directory Manipulation
file.show | Display One or More Files
file.symlink | File and Directory Manipulation
files | File and Directory Manipulation
findInterval | Find Interval Numbers or Indices
findRestart | Condition Handling and Recovery
finite | Finite, Infinite and NaN Numbers
floor | Rounding of Numbers
flush | Functions to Manipulate Connections
for | Control Flow
force | Force Evaluation of an Argument
Foreign | Foreign Function Interface
formals | Access to and Manipulation of the Formal Arguments
format | Encode in a Common Format
format.Date | Date Conversion Functions to and from Character
format.default | Encode in a Common Format
format.factor | Encode in a Common Format
format.hexmode | Display Numbers in Hexadecimal
format.info | format(.) Information
format.octmode | Display Numbers in Octal
format.POSIXct | Date-time Conversion Functions to and from Character
format.POSIXlt | Date-time Conversion Functions to and from Character
format.pval | Format P Values
formatC | Formatting Using C-style Formats
formatDL | Format Description Lists
forwardsolve | Solve an Upper or Lower Triangular System
function | Function Definition
fuzzy matching | Approximate String Matching (Fuzzy Matching)

-- G --

gamma | Special Functions of Mathematics
gammaCody | Bessel Functions
gc | Garbage Collection
gc.time | Report Time Spent in Garbage Collection
gcinfo | Garbage Collection
gctorture | Torture Garbage Collector
get | Return the Value of a Named Object
getAllConnections | Display Connections
getCallingDLL | Compute DLL for native interface call
getCallingDLLe | Compute DLL for native interface call
getCConverterDescriptions | Management of .C argument conversion list
getCConverterStatus | Management of .C argument conversion list
getConnection | Display Connections
getDLLRegisteredRoutines | Reflectance Information for C/Fortran routines in a DLL
geterrmessage | Stop Function Execution
getHook | Functions to Get and Set Hooks for Load, Attach, Detach and Unload
getLoadedDLLs | Get DLLs Loaded in Current Session
getNativeSymbolInfo | Obtain a Description of one or more Native (C/Fortran) Symbols
getNumCConverters | Management of .C argument conversion list
getOption | Options Settings
getRversion | Package versions
getTaskCallbackNames | Query the names of the current internal top-level task callbacks
gettext | Translate Text Messages
gettextf | Use C-style String Formatting Commands
getwd | Get or Set Working Directory
gl | Generate Factor Levels
globalenv | Environment Access
gregexpr | Pattern Matching and Replacement
grep | Pattern Matching and Replacement
group generic | S3 Group Generic Functions
gsub | Pattern Matching and Replacement
gzcon | (De)compress I/O Through Connections
gzfile | Functions to Manipulate Connections

-- H --

hexmode Display Numbers in Hexadecimal

-- I --

I | Inhibit Interpretation/Conversion of Objects
iconv | Convert Character Vector between Encodings
iconvlist | Convert Character Vector between Encodings
identical | Test Objects for Exact Equality
if | Control Flow
ifelse | Conditional Element Selection
Im | Complex Vectors
Inf | Finite, Infinite and NaN Numbers
inherits | Object Classes
integer | Integer Vectors
interaction | Compute Factor Interactions
interactive | Is R Running Interactively?
internal generic | Internal Generic Functions
InternalGenerics | Internal Generic Functions
InternalMethods | Internal Generic Functions
intersect | Set Operations
intToBits | Convert to or from Raw Vectors
intToUtf8 | Convert to or from UTF-8-enconded Character Vectors
inverse.rle | Run Length Encoding
invisible | Change the Print Mode to Invisible
invokeRestart | Condition Handling and Recovery
invokeRestartInteractively | Condition Handling and Recovery
is.array | Multi-way Arrays
is.atomic | Is an Object Atomic or Recursive?
is.call | Function Calls
is.character | Character Vectors
is.complex | Complex Vectors
is.data.frame | Coerce to a Data Frame
is.double | Double Precision Vectors
is.element | Set Operations
is.environment | Environment Access
is.expression | Unevaluated Expressions
is.factor | Factors
is.finite | Finite, Infinite and NaN Numbers
is.function | Is an Object of Type (Primitive) Function?
is.infinite | Finite, Infinite and NaN Numbers
is.integer | Integer Vectors
is.language | Is an Object a Language Object?
is.list | Lists - Generic and Dotted Pairs
is.loaded | Foreign Function Interface
is.logical | Logical Vectors
is.matrix | Matrices
is.na | Not Available / ``Missing'' Values
is.na.POSIXlt | Date-Time Classes
is.name | Names and Symbols
is.nan | Finite, Infinite and NaN Numbers
is.null | The Null Object
is.numeric | Numeric Vectors
is.object | Is an Object ``internally classed''?
is.ordered | Factors
is.package_version | Package versions
is.pairlist | Lists - Generic and Dotted Pairs
is.primitive | Is an Object of Type (Primitive) Function?
is.qr | The QR Decomposition of a Matrix
is.R | Are we using R, rather than S?
is.real | Real Vectors
is.recursive | Is an Object Atomic or Recursive?
is.single | Is an Object of Single Precision Type?
is.symbol | Names and Symbols
is.table | Cross Tabulation and Table Creation
is.unsorted | Sorting or Ordering Vectors
is.vector | Vectors
isIncomplete | Functions to Manipulate Connections
ISOdate | Date-time Conversion Functions to and from Character
ISOdatetime | Date-time Conversion Functions to and from Character
isOpen | Functions to Manipulate Connections
isRestart | Condition Handling and Recovery
isS4 | Test for an S4 object
isSeekable | Functions to Reposition Connections
isSymmetric | Test if a Matrix or other Object is Symmetric
isTRUE | Logical Operators

-- J --

jitter | Add `Jitter' (Noise) to Numbers
julian | Extract Parts of a POSIXt or Date Object

-- K --

kappa | Estimate the Condition Number
kronecker | Kronecker products on arrays

-- L --

l10n_info | Localization Information
La.svd | Singular Value Decomposition of a Matrix
labels | Find Labels from Object
lapply | Apply a Function over a List or Vector
last.warning | Print Warning Messages
lbeta | Special Functions of Mathematics
lchoose | Special Functions of Mathematics
length | Length of an Object
LETTERS | Built-in Constants
letters | Built-in Constants
levels | Levels Attributes
lfactorial | Special Functions of Mathematics
lgamma | Special Functions of Mathematics
library | Loading and Listing of Packages
library.dynam | Loading Shared Libraries
licence | The R License Terms
license | The R License Terms
list | Lists - Generic and Dotted Pairs
list.files | List the Files in a Directory/Folder
load | Reload Saved Datasets
loadedNamespaces | Loading and Unloading Name Spaces
loadNamespace | Loading and Unloading Name Spaces
local | Evaluate an (Unevaluated) Expression
localeconv | Find Details of the Numerical and Monetary Representations in the Current Locale
locales | Query or Set Aspects of the Locale
log | Logarithms and Exponentials
log10 | Logarithms and Exponentials
log1p | Logarithms and Exponentials
log2 | Logarithms and Exponentials
logb | Logarithms and Exponentials
Logic | Logical Operators
logical | Logical Vectors
lower.tri | Lower and Upper Triangular Part of a Matrix
ls | List Objects

-- M --

make.names | Make Syntactically Valid Names
make.unique | Make Character Strings Unique
manglePackageName | Mangle the Package Name
mapply | Apply a function to multiple list or vector arguments
margin.table | Compute table margin
mat.or.vec | Create a Matrix or a Vector
match | Value Matching
match.arg | Argument Verification Using Partial Matching
match.call | Argument Matching
match.fun | Function Verification for ``Function Variables''
Math | S3 Group Generic Functions
Math.Date | Date Class
Math.difftime | Time Intervals
Math.factor | Factors
Math.POSIXlt | Date-Time Classes
Math.POSIXt | Date-Time Classes
matmult | Matrix Multiplication
matrix | Matrices
max | Maxima and Minima
max.col | Find Maximum Position in Matrix
mean | Arithmetic Mean
mean.Date | Date Class
mean.default | Arithmetic Mean
mean.difftime | Time Intervals
mean.POSIXct | Date-Time Classes
mean.POSIXlt | Date-Time Classes
mem.limits | Memory Available for Data Storage
Memory | Memory Available for Data Storage
Memory-limits | Memory Limits in R
memory.profile | Profile the Usage of Cons Cells
merge | Merge Two Data Frames
message | Diagnostic Messages
mget | Return the Value of a Named Object
min | Maxima and Minima
missing | Does a Formal Argument have a Value?
Mod | Complex Vectors
mode | The (Storage) Mode of an Object
month.abb | Built-in Constants
month.name | Built-in Constants
months | Extract Parts of a POSIXt or Date Object

-- N --

NA | Not Available / ``Missing'' Values
name | Names and Symbols
names | The Names of an Object
NaN | Finite, Infinite and NaN Numbers
nargs | The Number of Arguments to a Function
NativeSymbol | Obtain a Description of one or more Native (C/Fortran) Symbols
NativeSymbolInfo | Obtain a Description of one or more Native (C/Fortran) Symbols
nchar | Count the Number of Characters (Bytes)
NCOL | The Number of Rows/Columns of an Array
ncol | The Number of Rows/Columns of an Array
new.env | Environment Access
next | Control Flow
NextMethod | Class Methods
ngettext | Translate Text Messages
nlevels | The Number of Levels of a Factor
noquote | Class for ``no quote'' Printing of Character Strings
NotYetImplemented | Not Yet Implemented Functions and Unused Arguments
NotYetUsed | Not Yet Implemented Functions and Unused Arguments
NROW | The Number of Rows/Columns of an Array
nrow | The Number of Rows/Columns of an Array
NULL | The Null Object
numeric | Numeric Vectors
NumericConstants | Numeric Constants

-- O --

objects | List Objects
octmode | Display Numbers in Octal
oldClass | Object Classes
on.exit | Function Exit Code
open | Functions to Manipulate Connections
Ops | S3 Group Generic Functions
Ops.Date | Operators on the Date Class
Ops.difftime | Time Intervals
Ops.factor | Factors
Ops.ordered | Factors
Ops.package_version | Package versions
Ops.POSIXt | Date-Time Classes
options | Options Settings
order | Ordering Permutation
ordered | Factors
outer | Outer Product of Arrays

-- P --

packageEvent | Functions to Get and Set Hooks for Load, Attach, Detach and Unload
package_version | Package versions
packBits | Convert to or from Raw Vectors
pairlist | Lists - Generic and Dotted Pairs
Paren | Parentheses and Braces
parent.env | Environment Access
parent.frame | Functions to Access the Function Call Stack
parse | Parse Expressions
paste | Concatenate Strings
path.expand | Expand File Paths
pi | Built-in Constants
pipe | Functions to Manipulate Connections
pmatch | Partial String Matching
pmax | Maxima and Minima
pmin | Maxima and Minima
polyroot | Find Zeros of a Real or Complex Polynomial
pos.to.env | Convert Positions in the Search Path to Environments
POSIXct | Date-Time Classes
POSIXlt | Date-Time Classes
POSIXt | Date-Time Classes
pretty | Pretty Breakpoints
prettyNum | Formatting Using C-style Formats
primitive | Call a ``Primitive'' Internal Function
print | Print Values
print.AsIs | Inhibit Interpretation/Conversion of Objects
print.by | Apply a Function to a Data Frame split by Factors
print.condition | Condition Handling and Recovery
print.connection | Functions to Manipulate Connections
print.data.frame | Printing Data Frames
print.Date | Date Class
print.default | Default Printing
print.difftime | Time Intervals
print.DLLInfo | Get DLLs Loaded in Current Session
print.DLLInfoList | Get DLLs Loaded in Current Session
print.DLLRegisteredRoutines | Reflectance Information for C/Fortran routines in a DLL
print.factor | Print Values
print.hexmode | Display Numbers in Hexadecimal
print.htest | Print Values
print.libraryIQR | Loading and Listing of Packages
print.listof | Print Values
print.NativeRoutineList | Reflectance Information for C/Fortran routines in a DLL
print.noquote | Class for ``no quote'' Printing of Character Strings
print.octmode | Display Numbers in Octal
print.packageInfo | Loading and Listing of Packages
print.package_version | Package versions
print.POSIXct | Date-Time Classes
print.POSIXlt | Date-Time Classes
print.restart | Condition Handling and Recovery
print.rle | Run Length Encoding
print.simple.list | Print Values
print.summary.table}%% {print.table | Cross Tabulation and Table Creation
print.table | Print Values
print.warnings | Print Warning Messages
prmatrix | Print Matrices, Old-style
proc.time | Running Time of R
prod | Product of Vector Elements
promise | Delay Evaluation
promises | Delay Evaluation
prop.table | Express Table Entries as Fraction of Marginal Table
psigamma | Special Functions of Mathematics
pushBack | Push Text Back on to a Connection
pushBackLength | Push Text Back on to a Connection

-- Q --

q | Terminate an R Session
qr | The QR Decomposition of a Matrix
qr.Q | Reconstruct the Q, R, or X Matrices from a QR Object
qr.qty | The QR Decomposition of a Matrix
qr.qy | The QR Decomposition of a Matrix
qr.R | Reconstruct the Q, R, or X Matrices from a QR Object
qr.resid | The QR Decomposition of a Matrix
qr.solve | The QR Decomposition of a Matrix
qr.X | Reconstruct the Q, R, or X Matrices from a QR Object
quarters | Extract Parts of a POSIXt or Date Object
quit | Terminate an R Session
quote | Substituting and Quoting Expressions
Quotes | Quotes

-- R --

R.home | Return the R Home Directory
R.Version | Version Information
R.version | Version Information
Random.user | User-supplied Random Number Generation
range | Range of Values
rank | Sample Ranks
rapply | Recursively Apply a Function to a List
raw | Raw Vectors
rawShift | Convert to or from Raw Vectors
rawToBits | Convert to or from Raw Vectors
rawToChar | Convert to or from Raw Vectors
rbind | Combine R Objects by Rows or Columns
Rd2dvi | Utilities for Processing Rd Files
Rd2txt | Utilities for Processing Rd Files
Rdconv | Utilities for Processing Rd Files
Re | Complex Vectors
read.csv | Data Input
read.csv2 | Data Input
read.dcf | Read and Write Data in DCF Format
read.delim | Data Input
read.delim2 | Data Input
read.table | Data Input
readBin | Transfer Binary Data To and From Connections
readChar | Transfer Character Strings To and From Connections
readline | Read a Line from the Terminal
readLines | Read Text Lines from a Connection
real | Real Vectors
Recall | Recursive Calling
reg.finalizer | Finalization of Objects
regex | Regular Expressions as used in R
regexp | Regular Expressions as used in R
regexpr | Pattern Matching and Replacement
regular expression | Regular Expressions as used in R
remove | Remove Objects from a Specified Environment
removeCConverter | Management of .C argument conversion list
removeTaskCallback | Add or remove a top-level task callback
Renviron | Initialization at Start of an R Session
rep | Replicate Elements of Vectors and Lists
repeat | Control Flow
replace | Replace Values in a Vector
replicate | Apply a Function over a List or Vector
require | Loading and Listing of Packages
restartDescription | Condition Handling and Recovery
restartFormals | Condition Handling and Recovery
return | Function Definition
rev | Reverse Elements
rle | Run Length Encoding
rm | Remove Objects from a Specified Environment
RNG | Random Number Generation
RNGkind | Random Number Generation
RNGversion | Random Number Generation
round | Rounding of Numbers
round.Date | Round / Truncate Data-Time Objects
round.difftime | Time Intervals
round.POSIXt | Round / Truncate Data-Time Objects
row | Row Indexes
row.names | Get and Set Row Names for Data Frames
rowMeans | Form Row and Column Sums and Means
rownames | Row and Column Names
rowsum | Give column sums of a matrix or data frame, based on a grouping variable
rowSums | Form Row and Column Sums and Means
Rprofile | Initialization at Start of an R Session
R_HOME | Return the R Home Directory
R_LIBS | Loading and Listing of Packages

-- S --

S3groupGeneric | S3 Group Generic Functions
S3Methods | Class Methods
sample | Random Samples and Permutations
sapply | Apply a Function over a List or Vector
save | Save R Objects
scale | Scaling and Centering of Matrix-like Objects
scan | Read Data Values
Sd2Rd | Utilities for Processing Rd Files
search | Give Search Path for R Objects
searchpaths | Give Search Path for R Objects
seek | Functions to Reposition Connections
seq | Sequence Generation
seq.Date | Generate Regular Sequences of Dates
seq.default | Sequence Generation
seq.int | Sequence Generation
seq.POSIXt | Generate Regular Sequences of Dates
sequence | Create A Vector of Sequences
seq_along | Sequence Generation
seq_len | Sequence Generation
set.seed | Random Number Generation
setCConverterStatus | Management of .C argument conversion list
setdiff | Set Operations
setequal | Set Operations
setHook | Functions to Get and Set Hooks for Load, Attach, Detach and Unload
setwd | Get or Set Working Directory
shell | Invoke a System Command, using a Shell
shell.exec | Open a File or URL using Windows File Associations
showConnections | Display Connections
shQuote | Quote Strings for Use in OS Shells
sign | Sign Function
signalCondition | Condition Handling and Recovery
signif | Rounding of Numbers
simpleCondition | Condition Handling and Recovery
simpleError | Condition Handling and Recovery
simpleMessage | Condition Handling and Recovery
simpleWarning | Condition Handling and Recovery
sin | Trigonometric Functions
single | Double Precision Vectors
sinh | Hyperbolic Functions
sink | Send R Output to a File
slice.index | Slice Indexes in an Array
socketConnection | Functions to Manipulate Connections
socketSelect | Wait on Socket Connections
solve | Solve a System of Equations
solve.qr | The QR Decomposition of a Matrix
sort | Sorting or Ordering Vectors
sort.list | Ordering Permutation
sort.POSIXlt | Sorting or Ordering Vectors
source | Read R Code from a File or a Connection
Special | Special Functions of Mathematics
split | Divide into Groups
sprintf | Use C-style String Formatting Commands
sqrt | Miscellaneous Mathematical Functions
sQuote | Quote Text
stack | Stack or Unstack Vectors from a Data Frame or List
Startup | Initialization at Start of an R Session
stderr | Display Connections
stdin | Display Connections
stdout | Display Connections
stop | Stop Function Execution
stopifnot | Ensure the `Truth' of R Expressions
storage.mode | The (Storage) Mode of an Object
str.POSIXt | Date-Time Classes
strftime | Date-time Conversion Functions to and from Character
strptime | Date-time Conversion Functions to and from Character
strsplit | Split the Elements of a Character Vector
strtrim | Trim Character Strings to Specified Widths
structure | Attribute Specification
strwrap | Wrap Character Strings to Format Paragraphs
sub | Pattern Matching and Replacement
Subscript | Extract or Replace Parts of an Object
subset | Subsetting Vectors, Matrices and Data Frames
substitute | Substituting and Quoting Expressions
substr | Substrings of a Character Vector
substring | Substrings of a Character Vector
sum | Sum of Vector Elements
Summary | S3 Group Generic Functions
summary | Object Summaries
summary.connection | Functions to Manipulate Connections
Summary.data.frame | S3 Group Generic Functions
summary.data.frame | Object Summaries
Summary.Date | Date Class
summary.Date | Date Class
summary.default | Object Summaries
Summary.difftime | Time Intervals
Summary.factor | Factors
summary.factor | Object Summaries
summary.matrix | Object Summaries
Summary.package_version | Package versions
Summary.POSIXct | Date-Time Classes
summary.POSIXct | Date-Time Classes
Summary.POSIXlt | Date-Time Classes
summary.POSIXlt | Date-Time Classes
summary.table | Cross Tabulation and Table Creation
suppressMessages | Diagnostic Messages
suppressWarnings | Warning Messages
svd | Singular Value Decomposition of a Matrix
sweep | Sweep out Array Summaries
switch | Select One of a List of Alternatives
symbol | Names and Symbols
symbol.C | Deprecated Functions in Base package
symbol.For | Deprecated Functions in Base package
Syntax | Operator Syntax and Precedence
sys.call | Functions to Access the Function Call Stack
sys.calls | Functions to Access the Function Call Stack
Sys.Date | Get Current Date, Time and Timezone
sys.frame | Functions to Access the Function Call Stack
sys.frames | Functions to Access the Function Call Stack
sys.function | Functions to Access the Function Call Stack
Sys.getenv | Get Environment Variables
Sys.getlocale | Query or Set Aspects of the Locale
Sys.getpid | Get the Process ID of the R Session
Sys.info | Extract System and User Information
Sys.localeconv | Find Details of the Numerical and Monetary Representations in the Current Locale
sys.nframe | Functions to Access the Function Call Stack
sys.on.exit | Functions to Access the Function Call Stack
sys.parent | Functions to Access the Function Call Stack
sys.parents | Functions to Access the Function Call Stack
Sys.putenv | Set Environment Variables
Sys.setlocale | Query or Set Aspects of the Locale
Sys.sleep | Suspend Execution for a Time Interval
sys.source | Parse and Evaluate Expressions from a File
sys.status | Functions to Access the Function Call Stack
Sys.time | Get Current Date, Time and Timezone
Sys.timezone | Get Current Date, Time and Timezone
system | Invoke a System Command
system.file | Find Names of R System Files
system.time | CPU Time Used

-- T --

T | Logical Vectors
t | Matrix Transpose
table | Cross Tabulation and Table Creation
tabulate | Tabulation for Vectors
tan | Trigonometric Functions
tanh | Hyperbolic Functions
tapply | Apply a Function Over a ``Ragged'' Array
taskCallbackManager | Create an R-level task callback manager
tcrossprod | Matrix Crossproduct
tempdir | Create Names for Temporary Files
tempfile | Create Names for Temporary Files
textConnection | Text Connections
textConnectionValue | Text Connections
tilde | Tilde Operator
tolower | Character Translation and Casefolding
topenv | Top Level Environment
toString | Convert an R Object to a Character String
toupper | Character Translation and Casefolding
trace | Interactive Tracing and Debugging of Calls to a Function or Method
traceback | Print Call Stacks
tracingState | Interactive Tracing and Debugging of Calls to a Function or Method
transform | Transform an Object, for Example a Data Frame
Trig | Trigonometric Functions
trigamma | Special Functions of Mathematics
TRUE | Logical Vectors
trunc | Rounding of Numbers
trunc.Date | Round / Truncate Data-Time Objects
trunc.POSIXt | Round / Truncate Data-Time Objects
truncate | Functions to Reposition Connections
try | Try an Expression Allowing Error Recovery
tryCatch | Condition Handling and Recovery
type | The Type of an Object
type.convert | Type Conversion on Character Variables
typeof | The Type of an Object

-- U --

unclass | Object Classes
undebug | Debug a Function
union | Set Operations
unique | Extract Unique Elements
unique.POSIXlt | Date-Time Classes
unix | Invoke a System Command
unix.time | CPU Time Used
unlink | Delete Files and Directories
unlist | Flatten Lists
unloadNamespace | Loading and Unloading Name Spaces
unname | Remove `names' or `dimnames'
unsplit | Divide into Groups
unstack | Stack or Unstack Vectors from a Data Frame or List
untrace | Interactive Tracing and Debugging of Calls to a Function or Method
unz | Functions to Manipulate Connections
upper.tri | Lower and Upper Triangular Part of a Matrix
url | Functions to Manipulate Connections
UseMethod | Class Methods
utf8ToInt | Convert to or from UTF-8-enconded Character Vectors

-- V --

vector | Vectors
Vectorize | Apply a function to multiple list or vector arguments
version | Version Information

-- W --

warning | Warning Messages
warnings | Print Warning Messages
weekdays | Extract Parts of a POSIXt or Date Object
which | Which indices are TRUE?
which.max | Where is the Min() or Max() ?
which.min | Where is the Min() or Max() ?
while | Control Flow
with | Evaluate an Expression in a Data Environment
withCallingHandlers | Condition Handling and Recovery
withRestarts | Condition Handling and Recovery
write | Write Data to a File
write.csv | Data Output
write.csv2 | Data Output
write.dcf | Read and Write Data in DCF Format
write.table | Data Output
writeBin | Transfer Binary Data To and From Connections
writeChar | Transfer Character Strings To and From Connections
writeLines | Write Lines to a Connection

-- X --

xor Logical Operators

-- Z --

zapsmall | Rounding of Numbers
zip.file.extract | Extract File from a Zip Archive

-- misc --

[ | Extract or Replace Parts of an Object
[.AsIs | Inhibit Interpretation/Conversion of Objects
[.data.frame | Extract or Replace Parts of a Data Frame
[.Date | Date Class
[.difftime | Time Intervals
[.factor | Extract or Replace Parts of a Factor
[.hexmode | Display Numbers in Hexadecimal
[.noquote | Class for ``no quote'' Printing of Character Strings
[.octmode | Display Numbers in Octal
[.package_version | Package versions
[.POSIXct | Date-Time Classes
[.POSIXlt | Date-Time Classes
[[ | Extract or Replace Parts of an Object
[[.data.frame | Extract or Replace Parts of a Data Frame
[[.Date | Date Class
[[.factor | Extract or Replace Parts of a Factor
[[.package_version | Package versions
[[.POSIXct | Date-Time Classes
^ | Arithmetic Operators
` | Quotes
{ | Parentheses and Braces
| | Logical Operators
|| | Logical Operators
~ | Tilde Operator


Abbreviate Strings

Description

Abbreviate strings to at least minlength characters, such that they remain unique (if they were).

Usage

abbreviate(names.arg, minlength = 4, use.classes = TRUE,
           dot = FALSE)

Arguments

names.arg | a character vector of names to be abbreviated, or an object to be coerced to a character vector by as.character.
minlength | the minimum length of the abbreviations.
use.classes | logical (currently ignored by R).
dot | logical; should a dot (".") be appended?

Details

The algorithm used is similar to that of S. First spaces at the beginning of the word are stripped. Then any other spaces are stripped. Next lower case vowels are removed followed by lower case consonants. Finally if the abbreviation is still longer than minlength upper case letters are stripped.

Letters are always stripped from the end of the word first. If an element of names.arg contains more than one word (words are separated by space) then at least one letter from each word will be retained. If a single string is passed it is abbreviated in the same manner as a vector of strings.

Missing (NA) values are not abbreviated.

If use.classes is FALSE then the only distinction is to be between letters and space. This has NOT been implemented.

There is a limit on 8191 bytes on the elements of names.arg (after possible coercion).

Value

A character vector containing abbreviations for the strings in its first argument. Duplicates in the original names.arg will be given identical abbreviations. If any non-duplicated elements have the same minlength abbreviations then minlength is incremented by one and new abbreviations are found for those elements only. This process is repeated until all unique elements of names.arg have unique abbreviations.
The character version of names.arg is attached to the returned value as a names argument: no other attributes are retained.

Warning

This is really only suitable for English, and does not work correctly with non-ASCII characters in UTF-8 locales. It will warns if used with non-ASCII characters.

See Also

substr.

Examples

x <- c("abcd", "efgh", "abce")
abbreviate(x, 2)

(st.abb <- abbreviate(state.name, 2))
table(nchar(st.abb))# out of 50, 3 need 4 letters
[Package base version 2.4.1 Index]


Approximate String Matching (Fuzzy Matching)

Description

Searches for approximate matches to pattern (the first argument) within the string x (the second argument) using the Levenshtein edit distance.

Usage

agrep(pattern, x, ignore.case = FALSE, value = FALSE,
      max.distance = 0.1)

Arguments

pattern | a non-empty character string to be matched (not a regular expression!). Coerced by as.character to a string if possible.
x | character vector where matches are sought. Coerced by as.character to a character vector if possible.
ignore.case | if FALSE, the pattern matching is case sensitive and if TRUE, case is ignored during matching.
value | if FALSE, a vector containing the (integer) indices of the matches determined is returned and if TRUE, a vector containing the matching elements themselves is returned.
max.distance Maximum distance allowed for a match. Expressed either as integer, or as a fraction of the pattern length (will be replaced by the smallest integer not less than the corresponding fraction), or a list with possible components
all:
maximal (overall) distance
insertions:
maximum number/fraction of insertions
deletions:
maximum number/fraction of deletions
substitutions:
maximum number/fraction of substitutions
If all is missing, it is set to 10%, the other components default to all. The component names can be abbreviated.

Details

The Levenshtein edit distance is used as measure of approximateness: it is the total number of insertions, deletions and substitutions required to transform one string into another.

The function is a simple interface to the apse library developed by Jarkko Hietaniemi (also used in the Perl String::Approx module).

Value

Either a vector giving the indices of the elements that yielded a match, of, if value is TRUE, the matched elements (after coercion, preserving names but no other attributes).

Author(s)

David Meyer David.Meyer@wu-wien.ac.at (based on C code by Jarkko Hietaniemi); modifications by Kurt Hornik.

See Also

grep

Examples

agrep("lasy", "1 lazy 2")
agrep("lasy", "1 lazy 2", max = list(sub = 0))
agrep("laysy", c("1 lazy", "1", "1 LAZY"), max = 2)
agrep("laysy", c("1 lazy", "1", "1 LAZY"), max = 2, value = TRUE)
agrep("laysy", c("1 lazy", "1", "1 LAZY"), max = 2, ignore.case = TRUE)


Are All Values True?

Description

Given a set of logical vectors, are all of the values true?

Usage

all(..., na.rm = FALSE)

Arguments

... | one or more logical vectors. Other objects are coerced in a similar way as as.logical.default.
na.rm | logical. If true NA values are removed before the result is computed.

Details

This is a generic function: methods can be defined for it directly or via the Summary group generic. For this to work properly, the arguments ... should be unnamed, and dispatch is on the first argument.

Value

Given a sequence of logical arguments, a logical value indicating whether or not all of the elements of x are TRUE.
The value returned is TRUE if all of the values in x are TRUE, and FALSE if any of the values in x are FALSE.
If na.rm = FALSE and x consists of a mix of TRUE and NA values, the value is NA.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

any, the “complement” of all, and stopifnot(*) which is an all(*) “insurance”.

Examples

range(x <- sort(round(rnorm(10) - 1.2, 1)))
if(all(x < 0)) cat("all x values are negative\n")


Test if Two Objects are (Nearly) Equal

Description

all.equal(x,y) is a utility to compare R objects x and y testing “near equality”. If they are different, comparison is still made to some extent, and a report of the differences is returned. Don't use all.equal directly in if expressions—either use isTRUE(all.equal(....)) or identical if appropriate.

Usage

all.equal(target, current, ...)

## S3 method for class 'numeric':
all.equal(target, current,
          tolerance = .Machine$double.eps ^ 0.5,
          scale = NULL, check.attributes = TRUE, ...)

attr.all.equal(target, current,
               check.attributes = TRUE, check.names = TRUE, ...)

Arguments

target | R object.
current | other R object, to be compared with target.
... | Further arguments for different methods, notably the following two, for numerical comparison:
tolerance | numeric >= 0. Differences smaller than tolerance are not considered.
scale | numeric scalar > 0 (or NULL). See Details.
check.attributes | logical indicating if the attributes(.) of target and current should be compared as well.
check.names | logical indicating if the names(.) of target and current should be compared as well (and separately from the attributes).

Details

There are several methods available, most of which are dispatched by the default method, see methods("all.equal"). all.equal.list and all.equal.language provide comparison of recursive objects.

Numerical comparisons for scale = NULL (the default) are done by first computing the mean absolute difference of the two numerical vectors. If this is smaller than tolerance or not finite, absolute differences are used, otherwise relative differences scaled by the mean absolute difference.

If scale is positive, absolute comparisons are made after scaling (dividing) by scale.

For complex arguments, the modulus Mod of the difference is used: all.equal.numeric is called so arguments tolerance and scale are available.

attr.all.equal is used for comparing attributes, returning NULL or character.

Value

Either TRUE or a vector of mode "character" describing the differences between target and current.

References

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language. Springer (for =).

See Also

identical, isTRUE, ==, and all for exact equality testing.

Examples

all.equal(pi, 355/113) # not precise enough (default tol) > relative error

d45 <- pi*(1/4 + 1:10)
stopifnot(
all.equal(tan(d45), rep(1,10)))        # TRUE, but
all      (tan(d45) == rep(1,10))       # FALSE, since not exactly
all.equal(tan(d45), rep(1,10), tol=0)  # to see difference


Find All Names in an Expression

Description

Return a character vector containing all the names which occur in an expression or call.

Usage

all.names(expr, functions = TRUE, max.names = 200, unique = FALSE)

all.vars(expr, functions = FALSE, max.names = 200, unique = TRUE)

Arguments

expr | an expression or call from which the names are to be extracted.
functions | a logical value indicating whether function names should be included in the result.
max.names | the maximum number of names to be returned.
unique | a logical value which indicates whether duplicate names should be removed from the value.

Details

These functions differ only in the default values for their arguments.

Value

A character vector with the extracted names.

Examples

all.names(expression(sin(x+y)))
all.vars(expression(sin(x+y)))


Are Some Values True?

Description

Given a set of logical vectors, are any of the values true?

Usage

any(..., na.rm = FALSE)

Arguments

... | one or more logical vectors. Other objects are coerced in a similar way as as.logical.default.
na.rm | logical. If true NA values are removed before the result is computed.

Details

This is a generic function: methods can be defined for it directly or via the Summary group generic. For this to work properly, the arguments ... should be unnamed, and dispatch is on the first argument.

Value

Given a sequence of logical arguments, a logical value indicating whether or not any of the elements of x are TRUE.
The value returned is TRUE if any of the values in x are TRUE, and FALSE if all of the values in x are FALSE.
If na.rm = FALSE and x consists of a mix of FALSE and NA values, the value is NA.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

all, the “complement” of any.

Examples

range(x <- sort(round(rnorm(10) - 1.2,1)))
if(any(x < 0)) cat("x contains negative values\n")


Array Transposition

Description

Transpose an array by permuting its dimensions and optionally resizing it.

Usage

aperm(a, perm, resize = TRUE)

Arguments

a | the array to be transposed.
perm | the subscript permutation vector, which must be a permutation of the integers 1:n, where n is the number of dimensions of a. The default is to reverse the order of the dimensions.
resize | a flag indicating whether the vector should be resized as well as having its elements reordered (default TRUE).

Value

A transposed version of array a, with subscripts permuted as indicated by the array perm. If resize is TRUE, the array is reshaped as well as having its elements permuted, the dimnames are also permuted; if resize = FALSE then the returned object has the same dimensions as a, and the dimnames are dropped. In each case other attributes are copied from a.
The function t provides a faster and more convenient way of transposing matrices.

Author(s)

Jonathan Rougier, J.C.Rougier@durham.ac.uk did the faster C implementation.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

t, to transpose matrices.

Examples

# interchange the first two subscripts on a 3-way array x
x  <- array(1:24, 2:4)
xt <- aperm(x, c(2,1,3))
stopifnot(t(xt[,,2]) == x[,,2],
          t(xt[,,3]) == x[,,3],
          t(xt[,,4]) == x[,,4])


Vector Merging

Description

Add elements to a vector.

Usage

append(x, values, after = length(x))

Arguments

x | the vector to be modified.
values | to be included in the modified vector.
after | a subscript, after which the values are to be appended.

Value

A vector containing the values in x with the elements of values appended after the specified element of x.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Examples

append(1:5, 0:1, after=3)


Apply Functions Over Array Margins

Description

Returns a vector or array or list of values obtained by applying a function to margins of an array.

Usage

apply(X, MARGIN, FUN, ...)

Arguments

X | the array to be used.
MARGIN | a vector giving the subscripts which the function will be applied over. 1 indicates rows, 2 indicates columns, c(1,2) indicates rows and columns.
FUN | the function to be applied: see Details. In the case of functions like +, %*%, etc., the function name must be backquoted or quoted.
... | optional arguments to FUN.

Details

If X is not an array but has a dimension attribute, apply attempts to coerce it to an array via as.matrix if it is two-dimensional (e.g., data frames) or via as.array.

FUN is found by a call to match.fun and typically is either a function or a symbol (e.g. a backquoted name) or a character string specifying a function to be searched for from the environment of the call to apply.

Value

If each call to FUN returns a vector of length n, then apply returns an array of dimension c(n, dim(X)[MARGIN]) if n > 1. If n equals 1, apply returns a vector if MARGIN has length 1 and an array of dimension dim(X)[MARGIN] otherwise. If n is 0, the result has length 0 but not necessarily the “correct” dimension.
If the calls to FUN return vectors of different lengths, apply returns a list of length prod(dim(X)[MARGIN]) with dim set to MARGIN if this has length greater than one.
In all cases the result is coerced by as.vector to one of the basic vector types before the dimensions are set, so that (for example) factor results will be coerced to a character array.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

lapply, tapply, and convenience functions sweep and aggregate.

Examples

## Compute row and column sums for a matrix:
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
dimnames(x)[[1]] <- letters[1:8]
apply(x, 2, mean, trim = .2)
col.sums <- apply(x, 2, sum)
row.sums <- apply(x, 1, sum)
rbind(cbind(x, Rtot = row.sums), Ctot = c(col.sums, sum(col.sums)))

stopifnot( apply(x, 2, is.vector)) # not ok in R <= 0.63.2

## Sort the columns of a matrix
apply(x, 2, sort)

##- function with extra args:
cave <- function(x, c1, c2) c(mean(x[c1]), mean(x[c2]))
apply(x,1, cave,  c1="x1", c2=c("x1","x2"))

ma <- matrix(c(1:4, 1, 6:8), nr = 2)
ma
apply(ma, 1, table)  #--> a list of length 2
apply(ma, 1, quantile)# 5 x n matrix with rownames

stopifnot(dim(ma) == dim(apply(ma, 1:2, sum)))## wasn't ok before R 0.63.1

## Example with different lengths for each call
z <- array(1:24, dim=2:4)
zseq <- apply(z, 1:2, function(x) seq(length=max(x)))
zseq         ## a 2 x 3 matrix
typeof(zseq) ## list
dim(zseq) ## 2 3
zseq[1,]
apply(z, 3, function(x) seq(length=max(x))) # a list without a dim attribute


Argument List of a Function

Description

Displays the argument names and corresponding default values of a function.

Usage

args(name)

Arguments

name an interpreted function. If name is a character string then the function with that name is found and used.

Details

This function is mainly used interactively. For programming, use formals instead.

Value

A function with identical formal argument list but an empty body if given an interpreted function; NULL in case of a variable or primitive (non-interpreted) function.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

formals, help.

Examples

args(c)            # -> NULL (c is a 'primitive' function)
args(graphics::plot.default)


Arithmetic Operators

Description

These binary operators perform arithmetic on numeric or complex vectors (or objects which can be coerced to them).

Usage

x + y
x - y
x * y
x / y
x ^ y
x %% y
x %/% y

Arguments

x, y numeric or complex vectors or objects which can be coerced to such, or other objects for which methods have been written.

Details

The binary arithmetic operators are generic functions: methods can be written for them individually or via the Ops group generic function. (See Ops for how dispatch is computed.)

If applied to arrays the result will be an array if this is sensible (for example it will not if the recycling rule has been invoked).

Logical vectors will be coerced to numeric vectors, FALSE having value 0 and TRUE having value one.

1 ^ y and y ^ 0 are 1, always. x ^ y should also give the proper “limit” result when either argument is infinite (i.e., +- Inf).

Objects such as arrays or time-series can be operated on this way provided they are conformable.

For real arguments, %% can be subject to catastrophic loss of accuracy if x is much larger than y, and a warning is given if this is detected.

Value

These operators return vectors containing the result of the element by element operations. The elements of shorter vectors are recycled as necessary (with a warning when they are recycled only fractionally). The operators are + for addition, - for subtraction, * for multiplication, / for division and ^ for exponentiation.
%% indicates x mod y and %/% indicates integer division. It is guaranteed that x == (x %% y) + y * ( x %/% y ) (up to rounding error) unless y == 0 where the result is NA or NaN (depending on the typeof of the arguments).
If either argument is complex the result will be complex, and if one or both arguments are numeric, the result will be numeric. If both arguments are integer, the result of / and ^ is numeric and of the other operators integer (with overflow returned as NA with a warning).
The rules for determining the attributes of the result are rather complicated. Most attributes are taken from the longer argument, the first if they are of the same length. Names will be copied from the first if it is the same length as the answer, otherwise from the second if that is. For time series, these operations are allowed only if the series are compatible, when the class and tsp attribute of whichever is a time series (the same, if both are) are used. For arrays (and an array result) the dimensions and dimnames are taken from first argument if it is an array, otherwise the second.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

sqrt for miscellaneous and Special for special mathematical functions.

Syntax for operator precedence.

%*% for matrix multiplication.

Examples

x <- -1:12
x + 1
2 * x + 3
x %% 2 #-- is periodic
x %/% 5


Multi-way Arrays

Description

Creates or tests for arrays.

Usage

array(data = NA, dim = length(data), dimnames = NULL)
as.array(x)
is.array(x)

Arguments

data | a vector (including a list) giving data to fill the array.
dim | the dim attribute for the array to be created, that is a vector of length one or more giving the maximal indices in each dimension.
dimnames | the names for the dimensions. This is a list with one component for each dimension, either NULL or a character vector of the length given by dim for that dimension. The list can be names, and the names will be used as names for the dimensions.
x | an R object.

Value

array returns an array with the extents specified in dim and naming information in dimnames. The values in data are taken to be those in the array with the leftmost subscript moving fastest. If there are too few elements in data to fill the array, then the elements in data are recycled. If data has length zero, NA of an appropriate type is used for atomic vectors (0 for raw vectors) and NULL for lists.
as.array() coerces its argument to be an array by attaching a dim attribute to it. It also attaches dimnames if x has names. The sole purpose of this is to make it possible to access the dim[names] attribute at a later time.
is.array returns TRUE or FALSE depending on whether its argument is an array (i.e., has a dim attribute) or not. It is generic: you can write methods to handle specific classes of objects, see InternalMethods.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

aperm, matrix, dim, dimnames.

Examples

dim(as.array(letters))
array(1:3, c(2,4)) # recycle 1:3 "2 2/3 times"
#     [,1] [,2] [,3] [,4]
#[1,]    1    3    2    1
#[2,]    2    1    3    2


Coerce to a Data Frame

Description

Functions to check if an object is a data frame, or coerce it if possible.

Usage

as.data.frame(x, row.names = NULL, optional = FALSE, ...)
## S3 method for class 'character':
as.data.frame(x, ...,
              stringsAsFactors = default.stringsAsFactors())
## S3 method for class 'matrix':
as.data.frame(x, row.names = NULL, optional = FALSE, ...,
                                 stringsAsFactors = default.stringsAsFactors())

is.data.frame(x)

Arguments

x | any R object.
row.names | NULL or a character vector giving the row names for the data frame. Missing values are not allowed.
optional | logical. If TRUE, setting row names and converting column names (to syntactic names) is optional.
... | additional arguments to be passed to or from methods.
stringsAsFactors | logical: should the character vector be converted to a factor?

Details

as.data.frame is a generic function with many methods, and users and packages can supply further methods.

If a list is supplied, each element is converted to a column in the data frame. Similarly, each column of a matrix is converted separately. This can be overridden if the object has a class which has a method for as.data.frame: two examples are matrices of class "model.matrix" (which are included as a single column) and list objects of class "POSIXlt" which are coerced to class "POSIXct".

Arrays can be converted to data frames. One-dimensional arrays are treated like vectors and two-dimensional arrays like matrices. Arrays with more than two dimensions are converted to matrices by ‘flattening’ all dimensions after the first and creating suitable column labels.

Character variables are converted to factor columns unless protected by I.

If a data frame is supplied, all classes preceding "data.frame" are stripped, and the row names are changed if that argument is supplied.

If row.names = NULL, row names are constructed from the names or dimnames of x, otherwise are the integer sequence starting at one. Few of the methods check for duplicated row names. Names are removed from vector columns unless I.

Value

as.data.frame returns a data frame, normally with all row names "" if optional = TRUE.
is.data.frame returns TRUE if its argument is a data frame (that is, has "data.frame" amongst its classes) and FALSE otherwise.

References

Chambers, J. M. (1992) Data for models. Chapter 3 of Statistical Models in S eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole.

See Also

data.frame, as.data.frame.table for the table method (which has additional arguments if called directly).


Coerce to an Environment Object

Description

Converts a number or a character string to the corresponding environment on the search path.

Usage

as.environment(object)

Arguments

object the object to convert. If it is already an environment, just return it. If it is a number, return the environment corresponding to that position on the search list. If it is a character string, match the string to the names on the search list.

Value

The corresponding environment object.

Author(s)

John Chambers

See Also

environment for creation and manipulation, search.

Examples

as.environment(1) ## the global environment
identical(globalenv(), as.environment(1)) ## is TRUE
try(as.environment("package:stats"))      ## stats need not be loaded


Convert Object to Function

Description

as.function is a generic function which is used to convert objects to functions.

as.function.default works on a list x, which should contain the concatenation of a formal argument list and an expression or an object of mode "call" which will become the function body. The function will be defined in a specified environment, by default that of the caller.

Usage

as.function(x, ...)

## Default S3 method:
as.function(x, envir = parent.frame(), ...)

Arguments

x | object to convert, a list for the default method.
... | additional arguments, depending on object
envir | environment in which the function should be defined

Value

The desired function.

Note

For ancient historical reasons, envir = NULL uses the global environment rather than the base environment. Please use envir = globalenv() instead if this is what you want, as the special handling of NULL may change in a future release.

Author(s)

Peter Dalgaard

See Also

function; alist which is handy for the construction of argument lists, etc.

Examples

as.function(alist(a=,b=2,a+b))
as.function(alist(a=,b=2,a+b))(3)


Date-time Conversion Functions

Description

Functions to manipulate objects of classes "POSIXlt" and "POSIXct" representing calendar dates and times.

Usage

as.POSIXct(x, tz = "")
as.POSIXlt(x, tz = "")

## S3 method for class 'POSIXlt':
as.numeric(x)

Arguments

x | An object to be converted.
tz | A timezone specification to be used for the conversion, if one is required. System-specific, but "" is the current timezone, and "GMT" is UTC (Coordinated Universal Time, in French).

Details

The as.POSIX* functions convert an object to one of the two classes used to represent date/times (calendar dates plus time to the nearest second). They can convert a wide variety of objects, including objects of the other class and of classes "Date", "date" (from package date or survival), "chron" and "dates" (from package chron) to these classes. Dates without times are treated as being at midnight UTC.

They can also convert character strings of the formats "2001-02-03" and "2001/02/03" optionally followed by white space and a time in the format "14:52" or "14:52:03". (Formats such as "01/02/03" are ambiguous but can be converted via a format specification by strptime.) (As from R 2.4.0 fractional seconds can be converted.)

Logical NAs can be converted to either of the classes, but no other logical vectors can be.

The as.numeric method converts "POSIXlt" objects to "POSIXct".

If you are given a numeric time as the number of seconds since an epoch, see the examples.

Where OSes describe their valid timezones can be obscure. The help for tzset (or _tzset on Windows) can be helpful, but it can also be inaccurate. There is a cumbersome POSIX specification, (listed under environment variable TZ at http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html), which is often at least partially supported, but there may be other more user-friendly ways to specify timezones. Windows documents a specification of the form GST-1GDT, but seems always to apply the US rules for changing to/from DST with such a specification. (There appears to be no documented way to apply timezones using other DST rules except to switch to the timezone, e.g. from the Control Panel.) So valid time zone values are of the forms EST5EDT for a timezone 5 hours west of GMT called EST when daylight saving is in force and EDT when it is not, HST10 for ‘Hawaii-Aleutian Standard Time’ (which has no DST), and CST-9:30 for the Northern Territory of Australia. The abbreviations have to be exactly 3 letters, and have no meaning other than as labels on the output.

Value

as.POSIXct and as.POSIXlt return an object of the appropriate class. If tz was specified, as.POSIXlt will give an appropriate "tzone" attribute.

Note

If you want to extract specific aspects of a time (such as the day of the week) just convert it to class "POSIXlt" and extract the relevant component(s) of the list, or if you want a character representation (such as a named day of the week) use format.POSIXlt or format.POSIXct.

If a timezone is needed and that specified is invalid on your system, what happens is system-specific but it will probably be ignored.

See Also

DateTimeClasses for details of the classes; strptime for conversion to and from character representations.

Examples

(z <- Sys.time())             # the current datetime, as class "POSIXct"
unclass(z)                    # a large integer
floor(unclass(z)/86400)       # the number of days since 1970-01-01
(z <- as.POSIXlt(Sys.time())) # the current datetime, as class "POSIXlt"
unlist(unclass(z))            # a list shown as a named vector

## suppose we have a time in seconds since 1960-01-01 00:00:00 GMT
z <- 1472562988
# two ways to convert this
ISOdatetime(1960,1,1,0,0,0) + z # late August 2006
strptime("1960-01-01", "%Y-%m-%d", tz="GMT") + z

as.POSIXlt(Sys.time(), "GMT") # the current time in GMT
as.POSIXlt(Sys.time(), "EST5EDT")  # the current time in New York
as.POSIXlt(Sys.time(), "HST10")    # the current time in Hawaii
as.POSIXlt(Sys.time(), "CST-9:30") # the current time in Darwin


Inhibit Interpretation/Conversion of Objects

Description

Change the class of an object to indicate that it should be treated “as is”.

Usage

I(x)

Arguments

x an object

Details

Function I has two main uses.

  • In function data.frame. Protecting an object by enclosing it in I() in a call to data.frame inhibits the conversion of character vectors to factors, and the dropping of names. I can also be used to protect objects which are to be added to a data frame, or converted to a data frame via as.data.frame.

    It achieves this by prepending the class "AsIs" to the object's classes. Class "AsIs" has a few of its own methods, including for [, as.data.frame, print and format.

  • In function formula. There it is used to inhibit the interpretation of operators such as "+", "-", "*" and "^" as formula operators, so they are used as arithmetical operators. This is interpreted as a symbol by terms.formula.

Value

A copy of the object with class "AsIs" prepended to the class(es).

References

Chambers, J. M. (1992) Linear models. Chapter 4 of Statistical Models in S eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole.

See Also

data.frame, formula


Assign a Value to a Name

Description

Assign a value to a name in an environment.

Usage

assign(x, value, pos = -1, envir = as.environment(pos),
       inherits = FALSE, immediate = TRUE)

Arguments

x | a variable name (given as a quoted string in the function call).
value | a value to be assigned to x.
pos | where to do the assignment. By default, assigns into the current environment. See the details for other possibilities.
envir | the environment to use. See the details section.
inherits | should the enclosing frames of the environment be inspected?
immediate | an ignored compatibility feature.

Details

The pos argument can specify the environment in which to assign the object in any of several ways: as an integer (the position in the search list); as the character string name of an element in the search list; or as an environment (including using sys.frame to access the currently active function calls). The envir argument is an alternative way to specify an environment, but is primarily there for back compatibility.

assign does not dispatch assignment methods, so it cannot be used to set elements of vectors, names, attributes, etc.

Note that assignment to an attached list or data frame changes the attached copy and not the original object: see attach.

Value

This function is invoked for its side effect, which is assigning value to the variable x. If no envir is specified, then the assignment takes place in the currently active environment.
If inherits is TRUE, enclosing environments of the supplied environment are searched until the variable x is encountered. The value is then assigned in the environment in which the variable is encountered (provided that the binding is not locked: see lockBinding: if it is, an error is signaled). If the symbol is not encountered then assignment takes place in the user's workspace (the global environment).
If inherits is FALSE, assignment takes place in the initial frame of envir, unless an existing binding is locked or there is no existing binding and the environment is locked.

Note

Prior to R 2.4.0 the base environment was ignored in the search for a binding by inherits = TRUE.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

<-, get, exists, environment.

Examples

for(i in 1:6) { #-- Create objects  'r.1', 'r.2', ... 'r.6' --
 nam <- paste("r",i, sep=".")
 assign(nam, 1:i)
}
ls(pat="^r..$")

##-- Global assignment within a function:
myf <- function(x) {
 innerf <- function(x) assign("Global.res", x^2, env = .GlobalEnv)
 innerf(x+1)
}
myf(3)
Global.res # 16

a <- 1:4
assign("a[1]", 2)
a[1] == 2          #FALSE
get("a[1]") == 2   #TRUE


Assignment Operators

Description

Assign a value to a name.

Usage

x <- value
x <<- value
value -> x
value ->> x

x = value

Arguments

x | a variable name (possibly quoted).
value | a value to be assigned to x.

Details

There are three different assignment operators: two of them have leftwards and rightwards forms.

The operators <- and = assign into the environment in which they are evaluated. The operator<- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

The operators <<- and ->> cause a search to made through the environment for an existing definition of the variable being assigned. If such a variable is found (and its binding is not locked) then its value is redefined, otherwise assignment takes place in the global environment. Note that their semantics differ from that in the S language, but are useful in conjunction with the scoping rules of R. See ‘The R Language Definition’ manual for further details and examples.

In all the assignment operator expressions, x can be a name or an expression defining a part of an object to be replaced (e.g., z[[1]]). A syntactic name does not need to be quoted, though it can be (preferably by backticks).

The leftwards forms of assignment <- = <<- group right to left, the other from left to right.

Value

value. Thus one can use a <- b <- c <- 6.

Note

Prior to R 2.4.0 the base environment was ignored in the search for a binding by <<- and ->>.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Chamber, J. M. (1998) Programming with Data. A Guide to the S Language. Springer (for =).

See Also

assign, environment.


Attach Set of R Objects to Search Path

Description

The database is attached to the R search path. This means that the database is searched by R when evaluating a variable, so objects in the database can be accessed by simply giving their names.

Usage

attach(what, pos = 2, name = deparse(substitute(what)),
       warn.conflicts = TRUE)

Arguments

what | “database”. This may currently be a data.frame or a list or a R data file created with save or NULL or an environment. See also Details.
pos | integer specifying position in search() where to attach.
name | alternative way to specify the database to be attached.
warn.conflicts | logical. If TRUE, warnings are printed about conflicts from attaching the database, unless that database contains an object .conflicts.OK. A conflict is a function masking a function, or a non-function masking a non-function.

Details

When evaluating a variable or function name R searches for that name in the databases listed by search. The first name of the appropriate type is used.

By attaching a data frame (or list) to the search path it is possible to refer to the variables in the data frame by their names alone, rather than as components of the data frame (e.g. in the example below, height rather than women$height).

By default the database is attached in position 2 in the search path, immediately after the user's workspace and before all previously loaded packages and previously attached databases. This can be altered to attach later in the search path with the pos option, but you cannot attach at pos=1.

The database is not actually attached. Rather, a new environment is created on the search path and the elements of a list (including columns of a data frame) or objects in a save file or an environment are copied into the new environment. If you use <<- or assign to assign to an attached database, you only alter the attached copy, not the original object. (Normal assignment will place a modified version in the user's workspace: see the examples.) For this reason attach can lead to confusion.

One useful ‘trick’ is to use what = NULL (or equivalently a length-zero list) to create a new environment on the search path into which objects can be assigned by assign or load or sys.source.

There are hooks to attach user-defined table objects of class "UserDefinedDatabase", supported by the Omegahat package RObjectTables. See http://www.omegahat.org/RObjectTables/.

Value

The environment is returned invisibly with a "name" attribute.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

library, detach, search, objects, environment, with.

Examples

summary(women$height)   # refers to variable 'height' in the data frame
attach(women)
summary(height)         # The same variable now available by name
height <- height*2.54   # Don't do this. It creates a new variable
                        # in the user's workspace
find("height")
summary(height)         # The new variable in the workspace
rm(height)
summary(height)         # The original variable.
height <<- height*25.4  # Change the copy in the attached environment
find("height")
summary(height)         # The changed copy
detach("women")
summary(women$height)   # unchanged

## Not run:
## create an environment on the search path and populate it
sys.source("myfuns.R", envir=attach(NULL, name="myfuns"))
## End(Not run)


Object Attributes

Description

Get or set specific attributes of an object.

Usage

attr(x, which)
attr(x, which) <- value

Arguments

x | an object whose attributes are to be accessed.
which | a non-empty character string specifying which attribute is to be accessed.
value | an object, the new value of the attribute, or NULL to remove the attribute.

Details

These functions provide access to a single attribute of an object. The replacement form causes the named attribute to take the value specified (or create a new attribute with the value given).

The extraction function first looks for an exact match to which amongst the attributes of x, then a unique partial match. The replacement function only uses exact matches.

Note that some attributes (namely class, comment, dim, dimnames, names, (from R 2.4.0) row.names and tsp) are treated specially and have restrictions on the values which can be set.

Specifying which as a character NA is interpreted as "NA" and not as a missing value.

Value

For the first form, the value of the attribute matched, or NULL if no exact match is found and no or more than one partial match is found.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

attributes

Examples

# create a 2 by 5 matrix
x <- 1:10
attr(x,"dim") <- c(2, 5)


Object Attribute Lists

Description

These functions access an object's attributes. The first form below returns the object's attribute list. The replacement forms uses the list on the right-hand side of the assignment as the object's attributes (if appropriate).

Usage

attributes(obj)
attributes(obj) <- value
mostattributes(obj) <- value

Arguments

obj | an object
value | an appropriate named list of attributes, or NULL.

Details

Note that some attributes (namely class, comment, dim, dimnames, names, (from R 2.4.0) row.names and tsp) are treated specially and have restrictions on the values which can be set.

Attributes are not stored internally as a list and should be thought of as a set and not a vector. They must have unique names (and NA is taken as "NA", not a missing value).

The mostattributes assignment takes special care for the dim, names and dimnames attributes, and assigns them only when valid whereas an attributes assignment would give an error if any are not.

The names of a pairlist are not stored as attributes, but are reported as if they were (and can be set by the replacement method for attributes).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

attr.

Examples

x <- cbind(a=1:3, pi=pi) # simple matrix w/ dimnames
attributes(x)

## strip an object's attributes:
attributes(x) <- NULL
x # now just a vector of length 6

mostattributes(x) <- list(mycomment = "really special", dim = 3:2,
   dimnames = list(LETTERS[1:3], letters[1:5]), names = paste(1:6))
x # dim(), but not {dim}names


On-demand Loading of Packages

Description

autoload creates a promise-to-evaluate autoloader and stores it with name name in .AutoloadEnv environment. When R attempts to evaluate name, autoloader is run, the package is loaded and name is re-evaluated in the new package's environment. The result is that R behaves as if file was loaded but it does not occupy memory.

.Autoloaded contains the “base names” of the packages for which autoloading has been promised.

Usage

autoload(name, package, reset = FALSE, ...)
autoloader(name, package, ...)

.AutoloadEnv
.Autoloaded

Arguments

name | string giving the name of an object.
package | string giving the name of a package containing the object.
reset | logical: for internal use by autoloader.
... | other arguments to library.

Value

This function is invoked for its side-effect. It has no return value.

See Also

delayedAssign, library

Examples

require(stats)
autoload("interpSpline", "splines")
search()
ls("Autoloads")
.Autoloaded

x <- sort(rnorm(12))
y <- x^2
is <- interpSpline(x,y)
search() ## now has splines
detach("package:splines")
search()
is2 <- interpSpline(x,y+x)
search() ## and again
detach("package:splines")


Solve an Upper or Lower Triangular System

Description

Solves a system of linear equations where the coefficient matrix is upper or lower triangular.

Usage

   backsolve(r, x, k=ncol(r), upper.tri=TRUE, transpose=FALSE)
forwardsolve(l, x, k=ncol(l), upper.tri=FALSE, transpose=FALSE)

Arguments

r,l | an upper (or lower) triangular matrix giving the coefficients for the system to be solved. Values below (above) the diagonal are ignored.
x | a matrix whose columns give “right-hand sides” for the equations.
k | The number of columns of r and rows of x to use.
upper.tri | logical; if TRUE (default), the upper triangular part of r is used. Otherwise, the lower one.
transpose | logical; if TRUE, solve r' * y = x for y, i.e., t(r) %*% y == x.

Value

The solution of the triangular system. The result will be a vector if x is a vector and a matrix if x is a matrix.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Dongarra, J. J., Bunch,J. R., Moler, C. B. and Stewart, G. W. (1978) LINPACK Users Guide. Philadelphia: SIAM Publications.

See Also

chol, qr, solve.

Examples

## upper triangular matrix 'r':
r <- rbind(c(1,2,3),
           c(0,1,1),
           c(0,0,2))
( y <- backsolve(r, x <- c(8,4,2)) ) # -1 3 1
r %*% y # == x = (8,4,2)
backsolve(r, x, transpose = TRUE) # 8 -12 -5


Defunct Functions in Base Package

Description

The functions or variables listed here are no longer part of R as they are not needed (any more).

Usage

Version()
provide(package)
.Provided
category(...)
print.anova.glm(.)
print.anova.lm(.)
print.tabular(.)
print.plot(.)
save.plot(.)
system.test(.)
getenv(...)
read.table.url(url, method,...)
scan.url(url, file = tempfile(), method, ...)
source.url(url, file = tempfile(), method, ...)
httpclient(url, port=80, error.is.fatal=TRUE, check.MIME.type=TRUE,
           file=tempfile(), drop.ctrl.z=TRUE)
parse.dcf(text = NULL, file = "", fields = NULL, versionfix = FALSE)
.Alias(expr)
print.ordered(.)
.Dyn.libs
.lib.loc
machine()
Machine()
Platform()
restart()
printNoClass(x, digits = NULL, quote = TRUE, na.print = NULL,
             print.gap = NULL, right = FALSE, ...)
codes(x, ...)
codes(x, ...) <- value
print.atomic(x, quote = TRUE, ...)
La.eigen(x, symmetric, only.values = FALSE, method = c("dsyevr", "dsyev"))
tetragamma(x)
pentagamma(x)
package.description(pkg, lib.loc = NULL, fields = NULL)
loadURL(url, envir = parent.frame(), quiet = TRUE, ...)
delay(x, env = .GlobalEnv)
format.char(x, width = NULL, flag = "-")
La.chol(x)
La.chol2inv(x, size = ncol(x))

Details

category has been an old-S function before there were factors; should be replaced by factor throughout!

The new function dev.print() should now be used for saving plots to a file or printing them.

provide and its object .Provided have been removed. They were never used for their intended purpose, to allow one package to subsume another.

getenv has been replaced by Sys.getenv.

*.url are replaced by calling read.table, scan or source on a url connection.

httpclient was used by the deprecated "socket" method of download.file.

parse.dcf has been replaced by read.dcf, which is much faster, but has a slightly different interface.

.Alias provided an unreliable way to create duplicate references to the same object. There is no direct replacement. Where multiple references to a single object are required for semantic reasons consider using environments or external pointers. There are some notes on http://developer.r-project.org.

.Dyn.libs and .lib.loc were internal variables used for storing and manipulating the information about packages with dynloaded shared libs, and the known R library trees. These are now dynamic variables which one can get or set using .dynLibs and .libPaths, respectively.

Machine() and Platform() were functions returning the variables .Machine and .Platform respectively.

restart() should be replaced by try(), in preparation for an exception-based implementation. If you use restart() in a way that cannot be replaced with try() then ask for help on r-devel.

printNoClass was in package methods and calls directly the internal function print.default.

codes was almost always used inappropriately. To get the internal coding of a factor, use unclass, as.vector or as.integer. For ordered factors, codes was equivalent to these, but for unordered factors it assumed an an alphabetical ordering of the levels in the locale in use.

print.atomic differed from print.default only in its argument sequence. It is not a method for print.

La.eigen has become the default for eigen.

tetragamma and pentagamma have been replaced by psigamma.

package.description has been replaced by packageDescription in utils.

loadURL has been superseded by load(url()).

delay has been replaced by delayedAssign. As from R 2.1.0 promises should never be visible unevaluated.

write.table0 was an R-level version of write.table provided for temporary back-compatibility.

format.char was an auxiliary function for formatC whose functionality (and more) is provided by format.default.

La.chol and La.chol2inv became the default methods for chol and chol2inv.

See Also

Defunct, base-deprecated


Deprecated Functions in Base package

Description

These functions are provided for compatibility with older versions of R only, and may be defunct as soon as the next release.

Usage

symbol.C(name)
symbol.For(name)

Arguments

name a character string giving either the name of a C function or Fortran subroutine.

Details

The original help page for these functions is often available at help("oldName-deprecated") (note the quotes). Functions in packages other than the base package are listed in help("pkg-deprecated").

Functions symbol.C and symbol.For are for historical compatibility with S. symbol.C just returns its argument unchanged, whereas symbol.For will map to lower case and append an underscore on those platforms (almost all) which do so for Fortran symbols. These are no longer of much use in R.

See Also

Deprecated, base-defunct


Internal Functions in the Base Package

Description

Internal functions in the base package, which are only user-visible because of the special nature of the base namespace.

Usage

.subset(x, ...)
.subset2(x, ...)

.find.package(package, lib.loc = NULL, quiet = FALSE,
              verbose = getOption("verbose"))

.path.package(package, quiet = FALSE)

.getRequiredPackages(file = "DESCRIPTION", quietly = FALSE,
                     useImports = FALSE)
.getRequiredPackages2(pkgInfo, quietly = FALSE, lib.loc = NULL,
                      useImports = FALSE)

testPlatformEquivalence(built, run)

.isMethodsDispatchOn(onOff = NULL)

sys.load.image(name, quiet)
sys.save.image(name)

Arguments

x | object from which to extract elements.
package | the name of a package.
lib.loc | a character vector describing the location of R library trees to search through, or NULL. The default value of NULL corresponds to all libraries currently known.
quiet | logical. Should this not give warnings or an error if the package(s) are not found?
useImports | logical. Should the Imports field be processed?
verbose | a logical. If TRUE, additional diagnostics are printed.
file | The full path to the ‘DESCRIPTION’ file of a package.
quietly | logical: should message(s) be printed.
pkginfo | A processed ‘DESCRIPTION’ file of class "packageDescription2".
built, run | platform strings of the form "cpu-vendor-os".
name | name of image file to save or load.

Details

The functions .subset and .subset2 are essentially equivalent to the [ and [[ operators, except methods that dispatch does not take place. This is to avoid expensive unclassing when applying the default method to an object. They should not normally be invoked by end users.

.find.package returns the paths to the locations where the given packages can be found. If lib.loc is NULL, then then attached packages are searched before the libraries. If a package is found more than once, the first match is used. Unless quiet = TRUE a warning will be given about the named packages which are not found, and an error if none are. If verbose is true, warnings about packages found more than once are given. It does know about versioned installs of packages, and for a package to be returned it must have a ‘DESCRIPTION’ file containing a valid version field. Where more than one versioned match is found to a unversioned name (and no exact match), the highest-numbered version is selected.

.path.package returns the paths from which the named packages were loaded, or if none were named, for all currently loaded packages. Unless quiet = TRUE it will warn if some of the packages named are not loaded, and given an error if none are. This function is not meant to be called by users, and its interface might change in future versions. Note that currently package must include the version mumber if versioned installs are used.

.getRequiredPackages2 attaches all the packages mentioned in the Depends field: failure to find a package is an error. It also checks the versions of the packages found against the Depends field.

.getRequiredPackages is a wrapper to .getRequiredPackages2 using a ‘DESCRIPTION’ file.

testPlatformEquivalence is used to test if a package with compiled code can safely be loaded into a build of R, which it does by comparing their ‘canonical’ "cpu-vendor-os" descriptions. The default function omits the vendor part and allows small mismatches elsewhere. Cognescenti can replace this function in the base namespace.

The function .isMethodsDispatchOn() returns TRUE if the S4 method dispatch has been turned on in the evaluator (usually by loading package methods). It is meant for R internal use only.

sys.save.image is a system function that is called by q() and its GUI analogs; sys.load.image is called by the startup code. These functions should not be called directly and are subject to change.

sys.save.image closes all connections first, to ensure that it is able to open a connection to save the image. This is appropriate when called from q() and allies, but reinforces the warning that it should not be called directly.

Value

.find.package and .path.packages return a character vector of paths to installed packages.
.getRequiredPackages and .getRequiredPackages2 return invisible().
testPlatformEquivalence: TRUE or FALSE.


The R Base Package

Description

Base R functions

Details

This package contains the basic functions which let R{} function as a language: arithmetic, input/output, basic programming support, etc. Its contents are available through inheritance from any environment.

For a complete list of functions, use library(help="base").


Manipulate File Paths

Description

basename removes all of the path up to the last path separator (if any).

dirname returns the part of the path up to (but excluding) the last path separator, or "." if there is no path separator.

Usage

basename(path)
dirname(path)

Arguments

path character vector, containing path names.

Details

For dirname tilde expansion is done: see the description of path.expand.

Trailing file separators are removed before dissecting the path, and for dirname any trailing file separators are removed from the result.

On Windows this will accept either \ or / as the directory separator, but dirname will return a path using / (except if a network share, when the leading \\ will be preserved).

Value

A character vector of the same length as path. A zero-length input will give a zero-length output with no error.

See Also

file.path, path.expand.

Examples

basename(file.path("","p1","p2","p3", c("file1", "file2")))
dirname(file.path("","p1","p2","p3","filename"))


Bessel Functions

Description

Bessel Functions of integer and fractional order, of first and second kind, J(nu) and Y(nu), and Modified Bessel functions (of first and third kind), I(nu) and K(nu).

gammaCody is the (Γ) function as from the Specfun package and originally used in the Bessel code.

Usage

besselI(x, nu, expon.scaled = FALSE)
besselK(x, nu, expon.scaled = FALSE)
besselJ(x, nu)
besselY(x, nu)
gammaCody(x)

Arguments

x | numeric, >= 0.
nu | numeric; The order (maybe fractional!) of the corresponding Bessel function.
expon.scaled | logical; if TRUE, the results are exponentially scaled in order to avoid overflow (I(nu)) or underflow (K(nu)), respectively.

Details

The underlying C code stems from Netlib (http://www.netlib.org/specfun/r[ijky]besl).

If expon.scaled = TRUE, exp(-x) I(x;nu), or exp(x) K(x;nu) are returned.

gammaCody may be somewhat faster but less precise and/or robust than R's standard gamma. It is here for experimental purpose mainly, and may be defunct very soon.

For nu < 0, formulae 9.1.2 and 9.6.2 from the reference below are applied (which is probably suboptimal), unless for besselK which is symmetric in nu.

Value

Numeric vector of the same length of x with the (scaled, if expon.scale=TRUE) values of the corresponding Bessel function.

Author(s)

Original Fortran code: W. J. Cody, Argonne National Laboratory
Translation to C and adaption to R: Martin Maechler maechler@stat.math.ethz.ch.

References

Abramowitz, M. and Stegun, I. A. (1972) Handbook of Mathematical Functions. Dover, New York; Chapter 9: Bessel Functions of Integer Order.

See Also

Other special mathematical functions, such as gamma, Γ(x), and beta, B(x).

Examples

nus <- c(0:5, 10, 20)

x <- seq(0, 4, len = 501)
plot(x, x, ylim = c(0, 6), ylab = "", type = "n",
     main = "Bessel Functions  I_nu(x)")
for(nu in nus) lines(x, besselI(x, nu=nu), col = nu+2)
legend(0, 6, legend = paste("nu=", nus), col = nus+2, lwd = 1)

x <- seq(0, 40, len=801); yl <- c(-.8, .8)
plot(x, x, ylim = yl, ylab = "", type = "n",
     main = "Bessel Functions  J_nu(x)")
for(nu in nus) lines(x, besselJ(x, nu=nu), col = nu+2)
legend(32,-.18, legend = paste("nu=", nus), col = nus+2, lwd = 1)

## Negative nu's :
xx <- 2:7
nu <- seq(-10, 9, len = 2001)
op <- par(lab = c(16, 5, 7))
matplot(nu, t(outer(xx, nu, besselI)), type = "l", ylim = c(-50, 200),
        main = expression(paste("Bessel ", I[nu](x), " for fixed ", x,
                                ",  as ", f(nu))),
        xlab = expression(nu))
abline(v=0, col = "light gray", lty = 3)
legend(5, 200, legend = paste("x=", xx), col=seq(xx), lty=seq(xx))
par(op)

x0 <- 2^(-20:10)
plot(x0, x0^-8, log="xy", ylab="",type="n",
     main = "Bessel Functions  J_nu(x)  near 0\n log - log  scale")
for(nu in sort(c(nus, nus+.5)))
    lines(x0, besselJ(x0, nu=nu), col = nu+2)
legend(3, 1e50, legend = paste("nu=", paste(nus, nus+.5, sep=",")),
       col = nus + 2, lwd = 1)

plot(x0, x0^-8, log="xy", ylab="", type="n",
     main = "Bessel Functions  K_nu(x)  near 0\n log - log  scale")
for(nu in sort(c(nus, nus+.5)))
    lines(x0, besselK(x0, nu=nu), col = nu+2)
legend(3, 1e50, legend = paste("nu=", paste(nus, nus+.5, sep=",")),
       col = nus + 2, lwd = 1)

x <- x[x > 0]
plot(x, x, ylim=c(1e-18, 1e11), log = "y", ylab = "", type = "n",
     main = "Bessel Functions  K_nu(x)")
for(nu in nus) lines(x, besselK(x, nu=nu), col = nu+2)
legend(0, 1e-5, legend=paste("nu=", nus), col = nus+2, lwd = 1)

yl <- c(-1.6, .6)
plot(x, x, ylim = yl, ylab = "", type = "n",
     main = "Bessel Functions  Y_nu(x)")
for(nu in nus){
    xx <- x[x > .6*nu]
    lines(xx, besselY(xx, nu=nu), col = nu+2)
}
legend(25, -.5, legend = paste("nu=", nus), col = nus+2, lwd = 1)


Binding and Environment Adjustments

Description

These functions represent an experimental interface for adjustments to environments and bindings within environments. They allow for locking environments as well as individual bindings, and for linking a variable to a function.

Usage

lockEnvironment(env, bindings = FALSE)
environmentIsLocked(env)
lockBinding(sym, env)
unlockBinding(sym, env)
bindingIsLocked(sym, env)
makeActiveBinding(sym, fun, env)
bindingIsActive(sym, env)

Arguments

env | an environment.
bindings | logical specifying whether bindings should be locked.
sym | a name object or character string
fun | a function taking zero or one arguments

Details

The function lockEnvironment locks its environment argument, which must be a normal environment (not base). (Locking the base environment and namespace may be supported later.) Locking the environment prevents adding or removing variable bindings from the environment. Changing the value of a variable is still possible unless the binding has been locked. The namespace environments of packages with namespaces are locked when loaded.

lockBinding locks individual bindings in the specified environment. The value of a locked binding cannot be changed. Locked bindings may be removed from an environment unless the environment is locked.

makeActiveBinding installs fun so that getting the value of sym calls fun with no arguments, and assigning to sym calls fun with one argument, the value to be assigned. This allows the implementation of things like C variables linked to R variables and variables linked to databases. It may also be useful for making thread-safe versions of some system globals.

Author(s)

Luke Tierney

Examples

# locking environments
e <- new.env()
assign("x", 1, env = e)
get("x", env = e)
lockEnvironment(e)
get("x", env = e)
assign("x", 2, env = e)
try(assign("y", 2, env = e)) # error

# locking bindings
e <- new.env()
assign("x", 1, env = e)
get("x", env = e)
lockBinding("x", e)
try(assign("x", 2, env = e)) # error
unlockBinding("x", e)
assign("x", 2, env = e)
get("x", env = e)

# active bindings
f <- local( {
    x <- 1
    function(v) {
       if (missing(v))
           cat("get\n")
       else {
           cat("set\n")
           x <<- v
       }
       x
    }
})
makeActiveBinding("fred", f, .GlobalEnv)
bindingIsActive("fred", .GlobalEnv)
fred
fred <- 2
fred


Access to and Manipulation of the Body of a Function

Description

Get or set the body of a function.

Usage

body(fun = sys.function(sys.parent()))
body(fun, envir = environment(fun)) <- value

Arguments

fun | a function object, or see Details.
envir | environment in which the function should be defined.
value | an expression or a list of R expressions.

Details

For the first form, fun can be a character string naming the function to be manipulated, which is searched for from the parent environment. If it is not specified, the function calling body is used.

Value

body returns the body of the function specified.
The replacement form sets the body of a function to the expression/list on the right hand side, and (potentially) resets the environment of the function.

See Also

alist, args, function.

Examples

body(body)
f <- function(x) x^5
body(f) <- expression(5^x)
## or equivalently  body(f) <- list(quote(5^x))
f(3) # = 125
body(f)


Partial substitution in expressions

Description

An analogue of the LISP backquote macro. bquote quotes its argument except that terms wrapped in .() are evaluated in the specified where environment.

Usage

bquote(expr, where = parent.frame())

Arguments

expr | A language object.
where | An environment.

Value

A language object.

See Also

quote, substitute

Examples

a <- 2

bquote(a == a)
quote(a == a)

bquote(a == .(a))
substitute(a == A, list(A = a))

plot(1:10, a*(1:10), main = bquote(a == .(a)))


Environment Browser

Description

Interrupt the execution of an expression and allow the inspection of the environment where browser was called from.

Usage

browser()

Details

A call to browser can be included in the body of a function. When reached, this causes a pause in the execution of the current expression and allows access to the R interpreter.

At the browser prompt the user can enter commands or R expressions. The commands are

c
(or just return) exit the browser and continue execution at the next statement.
cont
synonym for c.
n
enter the step-through debugger. This changes the meaning of c: see the documentation for debug.
where
print a stack trace of all active function calls.
Q
exit the browser and the current evaluation and return to the top-level prompt.
(Leading and trailing whitespace is ignored, except for return).

Anything else entered at the browser prompt is interpreted as an R expression to be evaluated in the calling environment: in particular typing an object name will cause the object to be printed, and ls() lists the objects in the calling frame. (If you want to look at an object with a name such as n, print it explicitly.)

The number of lines printed for the deparsed call can be limited by setting options(deparse.max.lines).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language. Springer.

See Also

debug, and traceback for the stack on error.


Returns the Names of All Built-in Objects

Description

Return the names of all the built-in objects. These are fetched directly from the symbol table of the R interpreter.

Usage

builtins(internal = FALSE)

Arguments

internal a logical indicating whether only “internal” functions (which can be called via .Internal) should be returned.

Details

builtins() returns an unsorted list of the objects in the symbol table, that is all the objects in the base environment. These are the built-in objects plus any that have been added subsequently when the base package was loaded. It is less confusing to use ls(baseenv(), all=TRUE).

builtins(TRUE) returns an unsorted list of the names of internal functions, that is those which can be accessed as .Internal(foo(args ...)) for foo in the list.

Value

A character vector.


Apply a Function to a Data Frame split by Factors

Description

Function by is an object-oriented wrapper for tapply applied to data frames.

Usage

by(data, INDICES, FUN, ...)

Arguments

data | an R object, normally a data frame, possibly a matrix.
INDICES | a factor or a list of factors, each of length nrow(data).
FUN | a function to be applied to data frame subsets of data.
... | further arguments to FUN.

Details

A data frame is split by row into data frames subsetted by the values of one or more factors, and function FUN is applied to each subset in turn.

Object data will be coerced to a data frame by default.

Value

A list of class "by", giving the results for each subset.

See Also

tapply

Examples

require(stats)
attach(warpbreaks)
by(warpbreaks[, 1:2], tension, summary)
by(warpbreaks[, 1], list(wool = wool, tension = tension), summary)
by(warpbreaks, tension, function(x) lm(breaks ~ wool, data = x))

## now suppose we want to extract the coefficients by group
tmp <- by(warpbreaks, tension, function(x) lm(breaks ~ wool, data = x))
sapply(tmp, coef)

detach("warpbreaks")


Combine Values into a Vector or List

Description

This is a generic function which combines its arguments.

The default method combines its arguments to form a vector. All arguments are coerced to a common type which is the type of the returned value, and all attributes except names are removed.

Usage

c(..., recursive=FALSE)

Arguments

... | objects to be concatenated.
recursive | logical. If recursive = TRUE, the function recursively descends through lists (and pairlists) combining all their elements into a vector.

Details

The output type is determined from the highest type of the components in the hierarchy NULL < raw < logical < integer < real < complex < character < list < expression. Pairlists are treated as lists, but non-vector components (such names and calls) are treated as one-element lists which cannot be unlisted even if recursive = TRUE.

c is sometimes used for its side effect of removing attributes except names, for example to turn an array into a vector. as.vector is a more intuitive way to do this, but also drops names.

Value

NULL or an expression or a vector of an appropriate mode.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

unlist and as.vector to produce attribute-free vectors.

Examples

c(1,7:9)
c(1:5, 10.5, "next")

## uses with a single argument to drop attributes
x <- 1:4
names(x) <- letters[1:4]
x
c(x)          # has names
as.vector(x)  # no names
dim(x) <- c(2,2)
x
c(x)
as.vector(x)

## append to a list:
ll <- list(A = 1, c="C")
## do *not* use
c(ll, d = 1:3) # which is == c(ll, as.list(c(d=1:3))
## but rather
c(ll, d = list(1:3))# c() combining two lists

c(list(A=c(B=1)), recursive=TRUE)

c(options(), recursive=TRUE)
c(list(A=c(B=1,C=2), B=c(E=7)), recursive=TRUE)


Function Calls

Description

Create or test for objects of mode "call".

Usage

call(name, ...)
is.call(x)
as.call(x)

Arguments

name | a character string naming the function to be called.
... | arguments to be part of the call.
x | an arbitrary R object.

Details

call returns an unevaluated function call, that is, an unevaluated expression which consists of the named function applied to the given arguments (name must be a quoted string which gives the name of a function to be called). Note that although the call is unevaluated, the arguments ... are evaluated.

call is a primitive, so the first argument (named or not) is taken as name and the remaining arguments as arguments for the constructed call: call(x="c", 1,3, name="foo") is a call to c and not to foo.

is.call is used to determine whether x is a call (i.e., of mode "call"). It is generic: you can write methods to handle specific classes of objects, see InternalMethods.

Objects of mode "list" can be coerced to mode "call". The first element of the list becomes the function part of the call, so should be a function or the name of one (as a symbol; a quoted string will not do).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

do.call for calling a function by name and argument list; Recall for recursive calling of functions; further is.language, expression, function.

Examples

is.call(call) #-> FALSE: Functions are NOT calls

## set up a function call to round with argument 10.5
cl <- call("round", 10.5)
is.call(cl)# TRUE
cl
## such a call can also be evaluated.
eval(cl)# [1] 10

A <- 10.5
call("round", A)        # round(10.5)
call("round", quote(A)) # round(A)
f <- "round"
call(f, quote(A))       # round(A)
## if we want to supply a function we need to use as.call or similar
f <- round
## Not run: call(f, quote(A))  # error: first arg must be character
(g <- as.call(list(f, quote(A))))
eval(g)
## alternatively but less transparently
g <- list(f, quote(A))
mode(g) <- "call"
g
eval(g)
## see also the examples in the help for do.call


Report Capabilities of this Build of R

Description

Report on the optional features which have been compiled into this build of R.

Usage

capabilities(what = NULL)

Arguments

what character vector or NULL, specifying required components. NULL implies that all are required.

Value

A named logical vector. Current components are

jpeg | Is the jpeg function operational?
png | Is the png function operational?
tcltk | Is the tcltk package operational?
X11 | (Unix) Are the X11 graphics device and the X11-based data editor available? This loads the X11 module if not already loaded, and checks that the default display can be contacted unless a X11 device has already been used.
http/ftp | Are url and the internal method for download.file available?
sockets | Are make.socket and related functions available?
libxml | Is there support for integrating libxml with the R event loop?
fifo | are FIFO connections supported?
cledit | Is command-line editing available in the current R session? This is false in non-interactive sessions.
iconv | is internationalization conversion via iconv supported?
NLS | is there Natural Language Support (for message translations)?

See Also

.Platform

Examples

capabilities()

if(!capabilities("http/ftp"))
   warning("internal download.file() is not available")

## See also the examples for 'connections'.


Concatenate and Print

Description

Outputs the objects, concatenating the representations. cat performs much less conversion than print.

Usage

cat(... , file = "", sep = " ", fill = FALSE, labels = NULL,
    append = FALSE)

Arguments

... | R objects (see Details for the types of objects allowed).
file | A connection, or a character string naming the file to print to. If "" (the default), cat prints to the standard output connection, the console unless redirected by sink.
sep | character string to insert between the objects to print.
fill | a logical or (positive) numeric controlling how the output is broken into successive lines. If FALSE (default), only newlines created explicitly by "\n" are printed. Otherwise, the output is broken into lines with print width equal to the option width if fill is TRUE, or the value of fill if this is numeric. Non-positive fill values are ignored, with a warning.
labels | character vector of labels for the lines printed. Ignored if fill is FALSE.
append | logical. Only used if the argument file is the name of file (and not a connection or "|cmd"). If TRUE output will be appended to file; otherwise, it will overwrite the contents of file.

Details

cat is useful for producing output in user-defined functions. It converts its arguments to character strings, concatenates them, separating them by the given sep= string, and then outputs them.

No linefeeds are output unless explicitly requested by "\n" or if generated by filling (if argument fill is TRUE or numeric.)

Currently only atomic vectors (and so not lists) and names are handled. Character strings are output ‘as is’ (unlike print.default which escapes non-printable characters and backslash — use encodeString if you want to output encoded strings using cat). Other types of R object should be converted (e.g. by as.character or format) before being passed to cat.

cat converts numeric/complex elements in the same way as print (and not in the same way as as.character which is used by the S equivalent), so options "digits" and "scipen" are relevant. However, it uses the minimum field width necessary for each element, rather than the same field width for all elements.

Value

None (invisible NULL).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

print, format, and paste which concatenates into a string.

Examples

iter <- rpois(1, lambda=10)
## print an informative message
cat("iteration = ", iter <- iter + 1, "\n")

## 'fill' and label lines:
cat(paste(letters, 100* 1:26), fill = TRUE,
    labels = paste("{",1:10,"}:",sep=""))


Combine R Objects by Rows or Columns

Description

Take a sequence of vector, matrix or data frames arguments and combine by columns or rows, respectively. These are generic functions with methods for other R classes.

Usage

cbind(..., deparse.level = 1)
rbind(..., deparse.level = 1)

Arguments

... | vectors or matrices. These can be given as named arguments. Other R objects will be coerced as appropriate: see section Details and Value. (For the "data.frame" method of cbind these can be further arguments to data.frame such as stringsAsFactors and check.names.)
deparse.level | integer controlling the construction of labels in the case of “non-matrix-like” arguments (i.e., for the default method): deparse.level = 0 constructs no labels; the default, deparse.level = 1 or 2 constructs labels from the argument names, see the ‘Value’ section below.

Details

The functions cbind and rbind are S3 generic, with methods for data frames. The data frame method will be used if at least one argument is a data frame and the rest are vectors or matrices. There can be other methods; in particular, there is one for time series objects.

In the default method, all the vectors/matrices must be atomic (see vector) or lists. Expressions are not allowed. Language objects (such as formulae and calls) and pairlists will be coerced to lists: other objects (such as names and external pointers) will be included as elements in a list result.

If there are several matrix arguments, they must all have the same number of columns (or rows) and this will be the number of columns (or rows) of the result. If all the arguments are vectors, the number of columns (rows) in the result is equal to the length of the longest vector. Values in shorter arguments are recycled to achieve this length (with a warning if they are recycled only fractionally).

When the arguments consist of a mix of matrices and vectors the number of columns (rows) of the result is determined by the number of columns (rows) of the matrix arguments. Any vectors have their values recycled or subsetted to achieve this length.

For cbind (rbind), vectors of zero length (including NULL) are ignored unless the result would have zero rows (columns), for S compatibility. (Zero-extent matrices do not occur in S3 and are not ignored in R.)

The rbind data frame method takes the classes of the columns from the first data frame, and matches columns by name (rather than by position). Factors have their levels expanded as necessary (in the order of the levels of the levelsets of the factors encountered) and the result is an ordered factor if and only if all the components were ordered factors. (The last point differs from S-PLUS.)

Value

A matrix or data frame combining the ... arguments column-wise or row-wise. (Exception: if all the inputs are NULL, the value is NULL.)
For cbind (rbind) the column (row) names are taken from the colnames (rownames) of the arguments if these are matrix-like. Otherwise from the names of the arguments or where those are not supplied and deparse.level > 0, by deparsing the expressions given, for deparse.level = 1 only if that gives a sensible name (a ‘symbol’, see is.symbol).
The names will depend on whether data frames are included: see the examples.
If a matrix is created, it will be a list if any of the inputs is not NULL nor an atomic vector. Otherwise its type is determined from the highest type of the inputs in the hierarchy NULL < raw < logical < integer < real < complex < character < list.

Note

The method dispatching is not done via UseMethod(), but by C-internal dispatching. Therefore, there is no need for, e.g., rbind.default.

The dispatch algorithm is described in the source file (‘.../src/main/bind.c’) as

  1. For each argument we get the list of possible class memberships from the class attribute.
  2. We inspect each class in turn to see if there is an an applicable method.
  3. If we find an applicable method we make sure that it is identical to any method determined for prior arguments. If it is identical, we proceed, otherwise we immediately drop through to the default code.

If you want to combine other objects with data frames, it may be necessary to coerce them to data frames first. (Note that this algorithm can result in calling the data frame method if the arguments are all either data frames or vectors, and this will result in the coercion of character vectors to factors.)

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

c to combine vectors (and lists) as vectors, data.frame to combine vectors and matrices as a data frame.

Examples

m <- cbind(1, 1:7) # the '1' (= shorter vector) is recycled
m
m <- cbind(m, 8:14)[, c(1, 3, 2)] # insert a column
m
cbind(1:7, diag(3))# vector is subset -> warning

cbind(0, rbind(1, 1:3))
cbind(I=0, X=rbind(a=1, b=1:3))  # use some names
xx <- data.frame(I=rep(0,2))
cbind(xx, X=rbind(a=1, b=1:3))   # named differently

cbind(0, matrix(1, nrow=0, ncol=4))#> Warning (making sense)
dim(cbind(0, matrix(1, nrow=2, ncol=0)))#-> 2 x 1

## deparse.level
dd <- 10
rbind(1:4, c=2, "a++" = 10, dd, deparse.level=0)# middle 2 rownames
rbind(1:4, c=2, "a++" = 10, dd, deparse.level=1)# 3 rownames (default)
rbind(1:4, c=2, "a++" = 10, dd, deparse.level=2)# 4 rownames


Expand a String with Respect to a Target Table

Description

Seeks a unique match of its first argument among the elements of its second. If successful, it returns this element; otherwise, it performs an action specified by the third argument.

Usage

char.expand(input, target, nomatch = stop("no match"))

Arguments

input | a character string to be expanded.
target | a character vector with the values to be matched against.
nomatch | an R expression to be evaluated in case expansion was not possible.

Details

This function is particularly useful when abbreviations are allowed in function arguments, and need to be uniquely expanded with respect to a target table of possible values.

See Also

charmatch and pmatch for performing partial string matching.

Examples

locPars <- c("mean", "median", "mode")
char.expand("me", locPars, warning("Could not expand!"))
char.expand("mo", locPars)


Character Vectors

Description

Create or test for objects of type "character".

Usage

character(length = 0)
as.character(x, ...)
is.character(x)

Arguments

length | desired length.
x | object to be coerced or tested.
... | further arguments passed to or from other methods.

Details

as.character and is.character are generic: you can write methods to handle specific classes of objects, see InternalMethods. Further, for as.character the default method calls as.vector, so dispatch is first on methods for as.character and then for methods for as.vector.

as.character represents real and complex numbers to 15 decimal places (technically the compiler's setting of the ISO C constant DBL_DIG, which will be 15 on machines supporting IEC60559 arithmetic according to the C99 standard). This ensures that all the digits in the result will be reliable (and not the result of representation error), but does mean that coversion to character and back to numeric may change the number. If you want to convert numbers to character with the maximum possible precision, use format.

Value

character creates a character vector of the specified length. The elements of the vector are all equal to "".
as.character attempts to coerce its argument to character type; like as.vector it strips attributes including names. For lists it deparses the elements individually, except that it extracts the first element of length-one character vectors.
is.character returns TRUE or FALSE depending on whether its argument is of character type or not. (Methods should always return FALSE for classes which are not based on a character vector, but can return FALSE even for those which are.)

Note

as.character truncates components of language objects to 500 characters (was about 70 before 1.3.1).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

paste, substr and strsplit for character concatenation and splitting, chartr for character translation and casefolding (e.g., upper to lower case) and sub, grep etc for string matching and substitutions. Note that help.search(keyword = "character") gives even more links. deparse, which is normally preferable to as.character for language objects.

Examples

form <- y ~ a + b + c
as.character(form)  ## length 3
deparse(form)       ## like the input

a0 <- 11/999          # has a repeating decimal representation
(a1 <- as.character(a0))
format(a0, digits=16) # shows one more digit
a2 <- as.numeric(a1)
a2 - a0               # normally around -1e-17
as.character(a2)      # normally different from a1
print(c(a0, a2), digits = 16)


Partial String Matching

Description

charmatch seeks matches for the elements of its first argument among those of its second.

Usage

charmatch(x, table, nomatch = NA)

Arguments

x | the values to be matched: converte to a character vector by as.character.
table | the values to be matched against: converted to a character vector.
nomatch | the value to be returned at non-matching positions.

Details

Exact matches are preferred to partial matches (those where the value to be matched has an exact match to the initial part of the target, but the target is longer).

If there is a single exact match or no exact match and a unique partial match then the index of the matching value is returned; if multiple exact or multiple partial matches are found then 0 is returned and if no match is found then nomatch is returned.

NA values are treated as the string constant "NA".

Author(s)

This function is based on a C function written by Terry Therneau.

See Also

pmatch, match.

grep or regexpr for more general (regexp) matching of strings.

Examples

charmatch("", "")                             # returns 1
charmatch("m",   c("mean", "median", "mode")) # returns 0
charmatch("med", c("mean", "median", "mode")) # returns 2


Character Translation and Casefolding

Description

Translate characters in character vectors, in particular from upper to lower case or vice versa.

Usage

chartr(old, new, x)
tolower(x)
toupper(x)
casefold(x, upper = FALSE)

Arguments

x | a character vector, or an object that can be coerced to character by as.character.
old | a character string specifying the characters to be translated.
new | a character string specifying the translations.
upper | logical: translate to upper or lower case?.

Details

chartr translates each character in x that is specified in old to the corresponding character specified in new. Ranges are supported in the specifications, but character classes and repeated characters are not. If old contains more characters than new, an error is signaled; if it contains fewer characters, the extra characters at the end of new are ignored.

tolower and toupper convert upper-case characters in a character vector to lower-case, or vice versa. Non-alphabetic characters are left unchanged.

casefold is a wrapper for tolower and toupper provided for compatibility with S-PLUS.

Value

A character vector of the same length and with the same attributes as x (after possible coercion).

See Also

sub and gsub for other substitutions in strings.

Examples

x <- "MiXeD cAsE 123"
chartr("iXs", "why", x)
chartr("a-cX", "D-Fw", x)
tolower(x)
toupper(x)

## "Mixed Case" Capitalizing - toupper( every first letter of a word ) :

.simpleCap <- function(x) {
  s <- strsplit(x, " ")[[1]]
  paste(toupper(substring(s, 1,1)), substring(s, 2), sep="", collapse=" ")
}
.simpleCap("the quick red fox jumps over the lazy brown dog")
## ->  [1] "The Quick Red Fox Jumps Over The Lazy Brown Dog"

## and the better, more sophisticated version:
capwords <- function(s, strict = FALSE) {
    cap <- function(s) paste(toupper(substring(s,1,1)),
                  {s <- substring(s,2); if(strict) tolower(s) else s},
                             sep = "", collapse = " " )
    sapply(strsplit(s, split = " "), cap, USE.NAMES = !is.null(names(s)))
}
capwords(c("using AIC for model selection"))
## ->  [1] "Using AIC For Model Selection"
capwords(c("using AIC", "for MODEL selection"), strict=TRUE)
## ->  [1] "Using Aic"  "For Model Selection"
##                ^^^        ^^^^^
##               'bad'       'good'


The Choleski Decomposition

Description

Compute the Choleski factorization of a real symmetric positive-definite square matrix.

Usage

chol(x, pivot = FALSE,  LINPACK = pivot)

Arguments

x | a real symmetric, positive-definite matrix
pivot | Should pivoting be used?
LINPACK | logical. Should LINPACK be used in the non-pivoting case (for compatibility with R < 1.7.0)?

Details

This is an interface to the LAPACK routine DPOTRF and the LINPACK routines DPOFA and DCHDC.

Note that only the upper triangular part of x is used, so that R'R = x when x is symmetric.

If pivot = FALSE and x is not non-negative definite an error occurs. If x is positive semi-definite (i.e., some zero eigenvalues) an error will also occur, as a numerical tolerance is used.

If pivot = TRUE, then the Choleski decomposition of a positive semi-definite x can be computed. The rank of x is returned as attr(Q, "rank"), subject to numerical errors. The pivot is returned as attr(Q, "pivot"). It is no longer the case that t(Q) %*% Q equals x. However, setting pivot <- attr(Q, "pivot") and oo <- order(pivot), it is true that t(Q[, oo]) %*% Q[, oo] equals x, or, alternatively, t(Q) %*% Q equals x[pivot, pivot]. See the examples.

Value

The upper triangular factor of the Choleski decomposition, i.e., the matrix R such that R'R = x (see example).
If pivoting is used, then two additional attributes "pivot" and "rank" are also returned.

Warning

The code does not check for symmetry.

If pivot = TRUE and x is not non-negative definite then there will be a warning message but a meaningless result will occur. So only use pivot = TRUE when x is non-negative definite by construction.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Dongarra, J. J., Bunch, J. R., Moler, C. B. and Stewart, G. W. (1978) LINPACK Users Guide. Philadelphia: SIAM Publications.

Anderson. E. and ten others (1999) LAPACK Users' Guide. Third Edition. SIAM.
Available on-line at http://www.netlib.org/lapack/lug/lapack_lug.html.

See Also

chol2inv for its inverse (without pivoting), backsolve for solving linear systems with upper triangular left sides.

qr, svd for related matrix factorizations.

Examples

( m <- matrix(c(5,1,1,3),2,2) )
( cm <- chol(m) )
t(cm) %*% cm  #-- = 'm'
crossprod(cm)  #-- = 'm'

# now for something positive semi-definite
x <- matrix(c(1:5, (1:5)^2), 5, 2)
x <- cbind(x, x[, 1] + 3*x[, 2])
m <- crossprod(x)
qr(m)$rank # is 2, as it should be

# chol() may fail, depending on numerical rounding:
# chol() unlike qr() does not use a tolerance.
try(chol(m))

(Q <- chol(m, pivot = TRUE)) # NB wrong rank here ... see Warning section.
## we can use this by
pivot <- attr(Q, "pivot")
oo <- order(pivot)
t(Q[, oo]) %*% Q[, oo] # recover m

## now for a non-positive-definite matrix
( m <- matrix(c(5,-5,-5,3),2,2) )
try(chol(m))  # fails
try(chol(m, LINPACK=TRUE))   # fails
(Q <- chol(m, pivot = TRUE)) # warning
crossprod(Q)  # not equal to m


Inverse from Choleski Decomposition

Description

Invert a symmetric, positive definite square matrix from its Choleski decomposition.

Usage

chol2inv(x, size = NCOL(x), LINPACK = FALSE)

Arguments

x | a matrix. The first size columns of the upper triangle contain the Choleski decomposition of the matrix to be inverted.
size | the number of columns of x containing the Choleski decomposition.
LINPACK | logical. Should LINPACK be used (for compatibility with R < 1.7.0)?

Details

This is an interface to the LAPACK routine DPOTRI and the LINPACK routine DPODI.

Value

The inverse of the matrix whose Choleski decomposition was given.

References

Dongarra, J. J., Bunch, J. R., Moler, C. B. and Stewart, G. W. (1978) LINPACK Users Guide. Philadelphia: SIAM Publications.

Anderson. E. and ten others (1999) LAPACK Users' Guide. Third Edition. SIAM. Available on-line at http://www.netlib.org/lapack/lug/lapack_lug.html.

See Also

chol, solve.

Examples

cma <- chol(ma  <- cbind(1, 1:3, c(1,3,7)))
ma %*% chol2inv(cma)


Object Classes

Description

R possesses a simple generic function mechanism which can be used for an object-oriented style of programming. Method dispatch takes place based on the class of the first argument to the generic function.

Usage

class(x)
class(x) <- value
unclass(x)
inherits(x, what, which = FALSE)

oldClass(x)
oldClass(x) <- value

Arguments

x | a R object
what, value | a character vector naming classes. value can also be NULL.
which | logical affecting return value: see Details.

Details

Many R objects have a class attribute, a character vector giving the names of the classes which the object “inherits” from. If the object does not have a class attribute, it has an implicit class, "matrix", "array" or the result of mode(x). (Functions oldClass and oldClass<- get and set the attribute, which can also be done directly.)

When a generic function fun is applied to an object with class attribute c("first", "second"), the system searches for a function called fun.first and, if it finds it, applies it to the object. If no such function is found, a function called fun.second is tried. If no class name produces a suitable function, the function fun.default is used (if it exists). If there is no class attribute, the implicit class is tried, then the default method.

The function class prints the vector of names of classes an object inherits from. Correspondingly, class<- sets the classes an object inherits from. Assigning a zero-length vector or NULL removes the class attribute.

unclass returns (a copy of) its argument with its class attribute removed. (It is not allowed for objects which cannot be copied, namely environments and external pointers.)

inherits indicates whether its first argument inherits from any of the classes specified in the what argument. If which is TRUE then an integer vector of the same length as what is returned. Each element indicates the position in the class(x) matched by the element of what; zero indicates no match. If which is FALSE then TRUE is returned by inherits if any of the names in what match with any class.

Formal classes

An additional mechanism of formal classes is available in packages methods which is attached by default. For objects which have a formal class, its name is returned by class as a character vector of length one.

The replacement version of the function sets the class to the value provided. For classes that have a formal definition, directly replacing the class this way is strongly deprecated. The expression as(object, value) is the way to coerce an object to a particular class.

Note

Functions oldClass and oldClass<- behave in the same way as functions of those names in S-PLUS 5/6, but in R UseMethod dispatches on the class as returned by class (with some interpolated classes: see the link) rather than oldClass. However, group generics dispatch on the oldClass for efficiency.

See Also

UseMethod, NextMethod, group generic.

Examples

x <- 10
inherits(x, "a") #FALSE
class(x) <- c("a", "b")
inherits(x,"a") #TRUE
inherits(x, "a", TRUE) # 1
inherits(x, c("a", "b", "c"), TRUE) # 1 2 0


Column Indexes

Description

Returns a matrix of integers indicating their column number in the matrix.

Usage

col(x, as.factor = FALSE)

Arguments

x | a matrix.
as.factor | a logical value indicating whether the value should be returned as a factor rather than as numeric.

Value

An integer matrix with the same dimensions as x and whose ij-th element is equal to j.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

row to get rows.

Examples

# extract an off-diagonal of a matrix
ma <- matrix(1:12, 3, 4)
ma[row(ma) == col(ma) + 1]

# create an identity 5-by-5 matrix
x <- matrix(0, nr = 5, nc = 5)
x[row(x) == col(x)] <- 1


Row and Column Names

Description

Retrieve or set the row or column names of a matrix-like object.

Usage

rownames(x, do.NULL = TRUE, prefix = "row")
rownames(x) <- value

colnames(x, do.NULL = TRUE, prefix = "col")
colnames(x) <- value

Arguments

x | a matrix-like R object, with at least two dimensions for colnames.
do.NULL | logical. Should this create names if they are NULL?
prefix | for created names.
value | a valid value for that component of dimnames(x). For a matrix or array this is either NULL or a character vector of non-zero length equal to the appropriate dimension.

Details

The extractor functions try to do something sensible for any matrix-like object x. If the object has dimnames the first component is used as the row names, and the second component (if any) is used for the col names. For a data frame, rownames and colnames are equivalent to row.names and names respectively, but the latter are preferred (and can be much faster).

If do.NULL is FALSE, a character vector (of length NROW(x) or NCOL(x)) is returned in any case, prepending prefix to simple numbers, if there are no dimnames or the corresponding component of the dimnames is NULL.

The replacement methods for arrays/matrices coerce vector and factor values of value to character, but do not dispatch methods for as.character.

For a data frame, value for rownames should be a character vector of non-duplicated and non-missing names (this is enforced), and for colnames a character vector of (preferably) unique syntactically-valid names. In both cases, value will be coerced by as.character.

See Also

dimnames, case.names, variable.names.

Examples

m0 <- matrix(NA, 4, 0)
rownames(m0)

m2 <- cbind(1,1:4)
colnames(m2, do.NULL = FALSE)
colnames(m2) <- c("x","Y")
rownames(m2) <- rownames(m2, do.NULL = FALSE, prefix = "Obs.")
m2


Colon Operator

Description

Generate regular sequences.

Usage

from:to
   a:b

Arguments

from | starting value of sequence.
to | (maximal) end value of the sequence.
a, b | factors of same length.

Details

The binary operator : has two meanings: for factors a:b is equivalent to interaction(a, b) (but the levels are ordered and labelled differently).

For numeric arguments from:to is equivalent to seq(from, to), and generates a sequence from from to to in steps of 1 or 1-. Value to will be included if it differs from from by an integer up to a numeric fuzz of about 1e-7.

Value

For numeric arguments, a numeric vector. This will be of type integer if from and to are both integers and representable in the integer type, otherwise of type numeric.
For factors, an unordered factor with levels labelled as la:lb and ordered lexicographically (that is, lb varies fastest).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.
(for numeric arguments: S does not have : for factors.)

See Also

seq.

As an alternative to using : for factors, interaction.

For : used in the formal representation of an interaction, see formula.

Examples

1:4
pi:6 # real
6:pi # integer

f1 <- gl(2,3); f1
f2 <- gl(3,2); f2
f1:f2 # a factor, the "cross"  f1 x f2


Form Row and Column Sums and Means

Description

Form row and column sums and means for numeric arrays.

Usage

colSums (x, na.rm = FALSE, dims = 1)
rowSums (x, na.rm = FALSE, dims = 1)
colMeans(x, na.rm = FALSE, dims = 1)
rowMeans(x, na.rm = FALSE, dims = 1)

Arguments

x | an array of two or more dimensions, containing numeric, complex, integer or logical values, or a numeric data frame.
na.rm | logical. Should missing values (including NaN) be omitted from the calculations?
dims | Which dimensions are regarded as “rows” or “columns” to sum over. For row*, the sum or mean is over dimensions dims+1, ...; for col* it is over dimensions 1:dims.

Details

These functions are equivalent to use of apply with FUN = mean or FUN = sum with appropriate margins, but are a lot faster. As they are written for speed, they blur over some of the subtleties of NaN and NA. If na.rm = FALSE and either NaN or NA appears in a sum, the result will be one of NaN or NA, but which might be platform-dependent.

Value

A numeric or complex array of suitable size, or a vector if the result is one-dimensional. The dimnames (or names for a vector result) are taken from the original array.
If there are no values in a range to be summed over (after removing missing values with na.rm = TRUE), that component of the output is set to 0 (*Sums) or NA (*Means), consistent with sum and mean.

See Also

apply, rowsum

Examples

## Compute row and column sums for a matrix:
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
rowSums(x); colSums(x)
dimnames(x)[[1]] <- letters[1:8]
rowSums(x); colSums(x); rowMeans(x); colMeans(x)
x[] <- as.integer(x)
rowSums(x); colSums(x)
x[] <- x < 3
rowSums(x); colSums(x)
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
x[3, ] <- NA; x[4, 2] <- NA
rowSums(x); colSums(x); rowMeans(x); colMeans(x)
rowSums(x, na.rm = TRUE); colSums(x, na.rm = TRUE)
rowMeans(x, na.rm = TRUE); colMeans(x, na.rm = TRUE)

## an array
dim(UCBAdmissions)
rowSums(UCBAdmissions); rowSums(UCBAdmissions, dims = 2)
colSums(UCBAdmissions); colSums(UCBAdmissions, dims = 2)

## complex case
x <- cbind(x1 = 3 + 2i, x2 = c(4:1, 2:5) - 5i)
x[3, ] <- NA; x[4, 2] <- NA
rowSums(x); colSums(x); rowMeans(x); colMeans(x)
rowSums(x, na.rm = TRUE); colSums(x, na.rm = TRUE)
rowMeans(x, na.rm = TRUE); colMeans(x, na.rm = TRUE)


Extract Command Line Arguments

Description

Provides access to a copy of the command line arguments supplied when this R session was invoked.

Usage

commandArgs()

Details

These arguments are captured before the standard R command line processing takes place. This means that they are the unmodified values. If it were useful, we could provide support an argument which indicated whether we want the unprocessed or processed values.

This is especially useful with the --args command-line flag to R, as all of the command line after than flag is skipped.

Value

A character vector containing the name of the executable and the user-supplied command line arguments. The first element is the name of the executable by which R was invoked. As far as I am aware, the exact form of this element is platform dependent. It may be the fully qualified name, or simply the last component (or basename) of the application.

See Also

Startup

Examples

commandArgs()
## Spawn a copy of this application as it was invoked.
## system(paste(commandArgs(), collapse=" "))


Query or Set a 'Comment' Attribute

Description

These functions set and query a comment attribute for any R objects. This is typically useful for data.frames or model fits.

Contrary to other attributes, the comment is not printed (by print or print.default).

Assigning NULL or a zero-length character vector removes the comment.

Usage

comment(x)
comment(x) <- value

Arguments

x | any R object
value | a character vector, or NULL.

See Also

attributes and attr for “normal” attributes.

Examples

x <- matrix(1:12, 3,4)
comment(x) <- c("This is my very important data from experiment #0234",
                "Jun 5, 1998")
x
comment(x)


Relational Operators

Description

Binary operators which allow the comparison of values in atomic vectors.

Usage

x < y
x > y
x <= y
x >= y
x == y
x != y

Arguments

x, y atomic vectors, or other objects for which methods have been written.

Details

The binary comparison operators are generic functions: methods can be written for them individually or via the Ops) group generic function. (See Ops for how dispatch is computed.)

Comparison of strings in character vectors is lexicographic within the strings using the collating sequence of the locale in use: see locales. The collating sequence of locales such as en_US is normally different from C (which should use ASCII) and can be surprising.

At least one of x and y must be an atomic vector, but if the other is a list R attempts to coerce it to the type of the atomic vector: this will succeed if the list is made up of elements of length one that can be coerced to the correct type.

If the two arguments are atomic vectors of different types, one is coerced to the type of the other, the (decreasing) order of precedence being character, complex, numeric, integer, logical and raw.

When comparisons are made between character strings, parts of the strings after embedded nul characters are ignored. (This is necessary as the position of nul in the collation sequence is undefined, and we want one of <, == and > to be true for any comparison.)

Missing values (NA) and NaN values are regarded as non-comparable even to themselves, so comparisons involving them will always result in NA. Missing values can also result when character strings are compared and one is not valid in the current collation locale.

Value

A vector of logicals indicating the result of the element by element comparison. The elements of shorter vectors are recycled as necessary.
Objects such as arrays or time-series can be compared this way provided they are conformable.

Note

Do not use == and != for tests, such as in if expressions, where you must get a single TRUE or FALSE. Unless you are absolutely sure that nothing unusual can happen, you should use the identical function instead.

For numerical and complex values, remember == and != do not allow for the finite representation of fractions, nor for rounding error. Using all.equal with identical is almost always preferable. See the examples.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

factor for the behaviour with factor arguments.

Syntax for operator precedence.

Examples

x <- rnorm(20)
x < 1
x[x > 0]

x1 <- 0.5 - 0.3
x2 <- 0.3 - 0.1
x1 == x2                           # FALSE on most machines
identical(all.equal(x1, x2), TRUE) # TRUE everywhere


Complex Vectors

Description

Basic functions which support complex arithmetic in R.

Usage

complex(length.out = 0, real = numeric(), imaginary = numeric(),
        modulus = 1, argument = 0)
as.complex(x, ...)
is.complex(x)

Re(x)
Im(x)
Mod(x)
Arg(x)
Conj(x)

Arguments

length.out | numeric. Desired length of the output vector, inputs being recycled as needed.
real | numeric vector.
imaginary | numeric vector.
modulus | numeric vector.
argument | numeric vector.
x | an object, probably of mode complex.
... | further arguments passed to or from other methods.

Details

Complex vectors can be created with complex. The vector can be specified either by giving its length, its real and imaginary parts, or modulus and argument. (Giving just the length generates a vector of complex zeroes.)

as.complex attempts to coerce its argument to be of complex type: like as.vector it strips attributes including names.

Note that is.complex and is.numeric are never both TRUE.

The functions Re, Im, Mod, Arg and Conj have their usual interpretation as returning the real part, imaginary part, modulus, argument and complex conjugate for complex values. Modulus and argument are also called the polar coordinates. If z = x + i y with real x and y, for r = Mod(z) = sqrt{x^2 + y^2}, and phi = Arg(z), x = r*cos(phi) and y = r*sin(phi). They are all generic functions: methods can be defined for them individually or via the Complex group generic.

In addition, the elementary trigonometric, logarithmic and exponential functions are available for complex values.

is.complex is generic: you can write methods to handle specific classes of objects, see InternalMethods.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Examples

0i ^ (-3:3)

matrix(1i^ (-6:5), nr=4)#- all columns are the same
0 ^ 1i # a complex NaN

## create a complex normal vector
z <- complex(real = rnorm(100), imag = rnorm(100))
## or also (less efficiently):
z2 <- 1:2 + 1i*(8:9)

## The Arg(.) is an angle:
zz <- (rep(1:4,len=9) + 1i*(9:1))/10
zz.shift <- complex(modulus = Mod(zz), argument= Arg(zz) + pi)
plot(zz, xlim=c(-1,1), ylim=c(-1,1), col="red", asp = 1,
     main = expression(paste("Rotation by "," ", pi == 180^o)))
abline(h=0,v=0, col="blue", lty=3)
points(zz.shift, col="orange")


Condition Handling and Recovery

Description

These functions provide a mechanism for handling unusual conditions, including errors and warnings.

Usage

tryCatch(expr, ..., finally)
withCallingHandlers(expr, ...)

signalCondition(cond)

simpleCondition(message, call = NULL)
simpleError    (message, call = NULL)
simpleWarning  (message, call = NULL)
simpleMessage  (message, call = NULL)

## S3 method for class 'condition':
as.character(x, ...)
## S3 method for class 'error':
as.character(x, ...)
## S3 method for class 'condition':
print(x, ...)
## S3 method for class 'restart':
print(x, ...)

conditionCall(c)
## S3 method for class 'condition':
conditionCall(c)
conditionMessage(c)
## S3 method for class 'condition':
conditionMessage(c)

withRestarts(expr, ...)

computeRestarts(cond = NULL)
findRestart(name, cond = NULL)
invokeRestart(r, ...)
invokeRestartInteractively(r)

isRestart(x)
restartDescription(r)
restartFormals(r)

.signalSimpleWarning(msg, call)
.handleSimpleError(h, msg, call)

Arguments

c | a condition object.
call | call expression.
cond | a condition object.
expr | expression to be evaluated.
finally | expression to be evaluated before returning or exiting.
h | function.
message | character string.
msg | character string.
name | character string naming a restart.
r | restart object.
x | object.
... | additional arguments; see details below.

Details

The condition system provides a mechanism for signaling and handling unusual conditions, including errors and warnings. Conditions are represented as objects that contain information about the condition that occurred, such as a message and the call in which the condition occurred. Currently conditions are S3-style objects, though this may eventually change.

Conditions are objects inheriting from the abstract class condition. Errors and warnings are objects inheriting from the abstract subclasses error and warning. The class simpleError is the class used by stop and all internal error signals. Similarly, simpleWarning is used by warning, and simpleMessage is used by message. The constructors by the same names take a string describing the condition as argument and an optional call. The functions conditionMessage and conditionCall are generic functions that return the message and call of a condition.

Conditions are signaled by signalCondition. In addition, the stop and warning functions have been modified to also accept condition arguments.

The function tryCatch evaluates its expression argument in a context where the handlers provided in the ... argument are available. The finally expression is then evaluated in the context in which tryCatch was called; that is, the handlers supplied to the current tryCatch call are not active when the finally expression is evaluated.

Handlers provided in the ... argument to tryCatch are established for the duration of the evaluation of expr. If no condition is signaled when evaluating expr then tryCatch returns the value of the expression.

If a condition is signaled while evaluating expr then established handlers are checked, starting with the most recently established ones, for one matching the class of the condition. When several handlers are supplied in a single tryCatch then the first one is considered more recent than the second. If a handler is found then control is transferred to the tryCatch call that established the handler, the handler found and all more recent handlers are disestablished, the handler is called with the condition as its argument, and the result returned by the handler is returned as the value of the tryCatch call.

Calling handlers are established by withCallingHandlers. If a condition is signaled and the applicable handler is a calling handler, then the handler is called by signalCondition in the context where the condition was signaled but with the available handlers restricted to those below the handler called in the handler stack. If the handler returns, then the next handler is tried; once the last handler has been tried, signalCondition returns NULL.

User interrupts signal a condition of class interrupt that inherits directly from class condition before executing the default interrupt action.

Restarts are used for establishing recovery protocols. They can be established using withRestarts. One pre-established restart is an abort restart that represents a jump to top level.

findRestart and computeRestarts find the available restarts. findRestart returns the most recently established restart of the specified name. computeRestarts returns a list of all restarts. Both can be given a condition argument and will then ignore restarts that do not apply to the condition.

invokeRestart transfers control to the point where the specified restart was established and calls the restart's handler with the arguments, if any, given as additional arguments to invokeRestart. The restart argument to invokeRestart can be a character string, in which case findRestart is used to find the restart.

New restarts for withRestarts can be specified in several ways. The simplest is in name=function form where the function is the handler to call when the restart is invoked. Another simple variant is as name=string where the string is stored in the description field of the restart object returned by findRestart; in this case the handler ignores its arguments and returns NULL. The most flexible form of a restart specification is as a list that can include several fields, including handler, description, and test. The test field should contain a function of one argument, a condition, that returns TRUE if the restart applies to the condition and FALSE if it does not; the default function returns TRUE for all conditions.

One additional field that can be specified for a restart is interactive. This should be a function of no arguments that returns a list of arguments to pass to the restart handler. The list could be obtained by interacting with the user if necessary. The function invokeRestartInteractively calls this function to obtain the arguments to use when invoking the restart. The default interactive method queries the user for values for the formal arguments of the handler function.

.signalSimpleWarning and .handleSimpleError are used internally and should not be called directly.

References

The tryCatch mechanism is similar to Java error handling. Calling handlers are based on Common Lisp and Dylan. Restarts are based on the Common Lisp restart mechanism.

See Also

stop and warning signal conditions, and try is essentially a simplified version of tryCatch.

Examples

tryCatch(1, finally=print("Hello"))
e <- simpleError("test error")
## Not run:
 stop(e)
 tryCatch(stop(e), finally=print("Hello"))
 tryCatch(stop("fred"), finally=print("Hello"))
## End(Not run)
tryCatch(stop(e), error = function(e) e, finally=print("Hello"))
tryCatch(stop("fred"),  error = function(e) e, finally=print("Hello"))
withCallingHandlers({ warning("A"); 1+2 }, warning = function(w) {})
{ try(invokeRestart("tryRestart")); 1}
## Not run:
 withRestarts(stop("A"), abort = function() {}); 1
## End(Not run)
withRestarts(invokeRestart("foo", 1, 2), foo = function(x, y) {x + y})


Search for Masked Objects on the Search Path

Description

conflicts reports on objects that exist with the same name in two or more places on the search path, usually because an object in the user's workspace or a package is masking a system object of the same name. This helps discover unintentional masking.

Usage

conflicts(where = search(), detail = FALSE)

Arguments

where | A subset of the search path, by default the whole search path.
detail | If TRUE, give the masked or masking functions for all members of the search path.

Value

If detail=FALSE, a character vector of masked objects. If detail=TRUE, a list of character vectors giving the masked or masking objects in that member of the search path. Empty vectors are omitted.

Examples

lm <- 1:3
conflicts(, TRUE)
## gives something like
# $.GlobalEnv
# [1] "lm"
#
# $package:base
# [1] "lm"

## Remove things from your "workspace" that mask others:
remove(list = conflicts(detail=TRUE)$.GlobalEnv)


Functions to Manipulate Connections

Description

Functions to create, open and close connections.

Usage

file(description = "", open = "", blocking = TRUE,
     encoding = getOption("encoding"))

pipe(description, open = "", encoding = getOption("encoding"))

fifo(description = "", open = "", blocking = FALSE,
     encoding = getOption("encoding"))

gzfile(description, open = "", encoding = getOption("encoding"),
       compression = 6)

unz(description, filename, open = "",
    encoding = getOption("encoding"))

bzfile(description, open = "", encoding = getOption("encoding"))

url(description, open = "", blocking = TRUE,
    encoding = getOption("encoding"))

socketConnection(host = "localhost", port, server = FALSE,
                 blocking = FALSE, open = "a+",
                 encoding = getOption("encoding"))

open(con, ...)
## S3 method for class 'connection':
open(con, open = "r", blocking = TRUE, ...)

close(con, ...)
## S3 method for class 'connection':
close(con, type = "rw", ...)

flush(con)

isOpen(con, rw = "")
isIncomplete(con)

Arguments

description | character. A description of the connection. For file and pipe this is a path to the file to be opened. For url it is a complete URL, including schemes (http://, ftp:// or file:// – see Details). file also accepts complete URLs.
filename | a filename within a zip file.
con | a connection.
host | character. Host name for port.
port | integer. The TCP port number.
server | logical. Should the socket be a client or a server?
open | character. A description of how to open the connection (if at all). See Details for possible values.
blocking | logical. See the ‘Blocking’ section below.
encoding | The name of the encoding to be used. See the ‘Encoding’ section below.
compression | integer in 0–9. The amount of compression to be applied when writing, from none to maximal. The default is a good space/time compromise.
type | character. Currently ignored.
rw | character. Empty or "read" or "write", partial matches allowed.
... | arguments passed to or from other methods.

Details

The first eight functions create connections. By default the connection is not opened (except for socketConnection), but may be opened by setting a non-empty value of argument open.

gzfile applies to files compressed by ‘gzip’, and bzfile to those compressed by ‘bzip2’. gzfile can also open uncompressed files. In each case the actual file is opened in binary mode and so no translations are done if the original file was a text file.

unz reads (only) single files within zip files, in binary mode. The description is the full path, with ‘.zip’ extension if required.

All platforms support file, gzfile, bzfile, unz and url("file://") connections. The other types may be partially implemented or not implemented at all. (They do work on most Unix platforms, and all but fifo on Windows.)

Proxies can be specified for url connections: see download.file.

open, close and seek are generic functions: the following applies to the methods relevant to connections.

open opens a connection. In general functions using connections will open them if they are not open, but then close them again, so to leave a connection open call open explicitly.

Possible values for the mode open to open a connection are

"r" or "rt"
Open for reading in text mode.
"w" or "wt"
Open for writing in text mode.
"a" or "at"
Open for appending in text mode.
"rb"
Open for reading in binary mode.
"wb"
Open for writing in binary mode.
"ab"
Open for appending in binary mode.
"r+", "r+b"
Open for reading and writing.
"w+", "w+b"
Open for reading and writing, truncating file initially.
"a+", "a+b"
Open for reading and appending.

Not all modes are applicable to all connections: for example URLs can only be opened for reading. Only file and socket connections can be opened for reading and writing/appending. For many connections there is little or no difference between text and binary modes, but there is for file-like connections on Windows, and pushBack is text-oriented and is only allowed on connections open for reading in text mode.

close closes and destroys a connection.

flush flushes the output stream of a connection open for write/append (where implemented).

If for a file connection the description is "", the file is immediately opened (in "w+" mode unless open="w+b" is specified) and unlinked from the file system. This provides a temporary file to write to and then read from.

A note on file:// URLs. The most general form (from RFC1738) is file://host/path/to/file, but R only accepts the form with an empty host field referring to the local machine. In this form the path is relative to the root of the filesystem, not a Windows concept. The standard form is file://d:/R/repos: for compatibility with earlier versions of R and Unix versions, any other form is parsed as R as file:// plus /path/to/file. Also, backslashes are accepted within the path even though RFC1738 does not allow them. Also, no attempt is made to decode an encoded URL: call URLdecode if necessary.

Value

file, pipe, fifo, url, gzfile, bzfile, unz and socketConnection return a connection object which inherits from class "connection" and has a first more specific class.
isOpen returns a logical value, whether the connection is currently open.
isIncomplete returns a logical value, whether last read attempt was blocked, or for an output text connection whether there is unflushed output.

Encoding

The encoding of the input/output stream of a connection in text mode can be specified by name, in the same way as it would be given to iconv: see that help page for how to find out what names are recognized on your platform. Additionally, "" and "native.enc" both mean the ‘native’ encoding, that is the internal encoding of the current locale and hence no translation is done.

Re-encoding only works for connections in text mode.

The encoding "UCS-2LE" is treated specially, as it is the appropriate value for Windows ‘Unicode’ text files. If the first two bytes are the Byte Order Mark 0xFFFE then these are removed as most implementations of iconv do not accept BOMs. Note that some implementations (including that used on Windows) will handle BOMs using encoding "UCS2" but many (including that in glibc) will not.

Exactly what happens when the requested translation cannot be done is in general undocumented. Requesting a conversion that is not supported is an error, reported when the connection is opened. On output the result is likely to be that up to the error, with a warning. On input, it will most likely be all or some of the input up to the error.

The encoding for stdin when redirected from a file can be set by the command-line flag --encoding.

Blocking

The default condition for all but fifo and socket connections is to be in blocking mode. In that mode, functions do not return to the R evaluator until they are complete. In non-blocking mode, operations return as soon as possible, so on input they will return with whatever input is available (possibly none) and for output they will return whether or not the write succeeded.

The function readLines behaves differently in respect of incomplete last lines in the two modes: see its help page.

Even when a connection is in blocking mode, attempts are made to ensure that it does not block the event loop and hence the operation of GUI parts of R. These do not always succeed, and the whole process will be blocked during a DNS lookup on Unix, for example.

Most blocking operations on URLs and sockets are subject to the timeout set by options("timeout"). Note that this is a timeout for no response at all, not for the whole operation.

Fifos

Fifos default to non-blocking. That follows Svr4 and it probably most natural, but it does have some implications. In particular, opening a non-blocking fifo connection for writing (only) will fail unless some other process is reading on the fifo.

Opening a fifo for both reading and writing (in any mode: one can only append to fifos) connects both sides of the fifo to the R process, and provides an similar facility to file().

Clipboard

file can also be used with description = "clipboard" in modes "r" and "w" only.

When a clipboard is opened for reading, the contents are immediately copied to internal storage in the connection.

When writing to the clipboard, the output is copied to the clipboard only when the connection is closed or flushed. There is a 32Kb limit on the text to be written to the clipboard. This can be raised by using e.g. file("clipboard-128") on NT-based versions of Windows, to give 128Kb.

At least on NT-based versions of Windows the clipboard works in Unicode wide characters, so encodings are likely not to work as one might expect.

Note

R's connections are modelled on those in S version 4 (see Chambers, 1998). However R goes well beyond the Svr4 model, for example in output text connections and URL, gzfile, bzfile and socket connections.

The default mode in R is "r" except for socket connections. This differs from Svr4, where it is the equivalent of "r+", known as "*".

On platforms where vsnprintf does not return the needed length of output there is a 100,000 character output limit on the length of line for fifo, gzfile and bzfile connections: longer lines will be truncated with a warning.

References

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language. Springer.

See Also

textConnection, seek, readLines, readBin, writeLines, writeBin, showConnections, pushBack.

capabilities to see if url, fifo and socketConnection are supported by this build of R.

To flush output to the console, see flush.console.

Examples

zz <- file("ex.data", "w")  # open an output file connection
cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
cat("One more line\n", file = zz)
close(zz)
readLines("ex.data")
unlink("ex.data")

zz <- gzfile("ex.gz", "w")  # compressed file
cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
close(zz)
readLines(zz <- gzfile("ex.gz"))
close(zz)
unlink("ex.gz")

zz <- bzfile("ex.bz2", "w")  # bzip2-ed file
cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
close(zz)
print(readLines(zz <- bzfile("ex.bz2")))
close(zz)
unlink("ex.bz2")

## An example of a file open for reading and writing
Tfile <- file("test1", "w+")
c(isOpen(Tfile, "r"), isOpen(Tfile, "w")) # both TRUE
cat("abc\ndef\n", file=Tfile)
readLines(Tfile)
seek(Tfile, 0, rw="r") # reset to beginning
readLines(Tfile)
cat("ghi\n", file=Tfile)
readLines(Tfile)
close(Tfile)
unlink("test1")

## We can do the same thing with an anonymous file.
Tfile <- file()
cat("abc\ndef\n", file=Tfile)
readLines(Tfile)
close(Tfile)

if(capabilities("fifo")) {
  zz <- fifo("foo", "w+")
  writeLines("abc", zz)
  print(readLines(zz))
  close(zz)
  unlink("foo")
}

## Not run: ## Unix examples of use of pipes

# read listing of current directory
readLines(pipe("ls -1"))

# remove trailing commas. Suppose
% cat data2
450, 390, 467, 654,  30, 542, 334, 432, 421,
357, 497, 493, 550, 549, 467, 575, 578, 342,
446, 547, 534, 495, 979, 479
# Then read this by
scan(pipe("sed -e s/,$// data2"), sep=",")

# convert decimal point to comma in output
# both R strings and (probably) the shell need \ doubled
zz <- pipe(paste("sed s/\\\\./,/ >", "outfile"), "w")
cat(format(round(rnorm(100), 4)), sep = "\n", file = zz)
close(zz)
file.show("outfile", delete.file=TRUE)## End(Not run)

## Not run: ## example for Unix machine running a finger daemon

con <- socketConnection(port = 79, blocking = TRUE)
writeLines(paste(system("whoami", intern=TRUE), "\r", sep=""), con)
gsub(" *$", "", readLines(con))
close(con)## End(Not run)

## Not run: ## two R processes communicating via non-blocking sockets
# R process 1
con1 <- socketConnection(port = 6011, server=TRUE)
writeLines(LETTERS, con1)
close(con1)

# R process 2
con2 <- socketConnection(Sys.info()["nodename"], port = 6011)
# as non-blocking, may need to loop for input
readLines(con2)
while(isIncomplete(con2)) {Sys.sleep(1); readLines(con2)}
close(con2)
## End(Not run)

## Not run:
 ## examples of use of encodings
cat(x, file = file("foo", "w", encoding="UTF-8"))
# read a 'Windows Unicode' file including names
A <- read.table(file("students", encoding="UCS-2LE"))
## End(Not run)


Built-in Constants

Description

Constants built into R.

Usage

LETTERS
letters
month.abb
month.name
pi

Details

R has a limited number of built-in constants (there is also a rather larger library of data sets which can be loaded with the function data).

The following constants are available:

  • LETTERS: the 26 upper-case letters of the Roman alphabet;
  • letters: the 26 lower-case letters of the Roman alphabet;
  • month.abb: the three-letter abbreviations for the English month names;
  • month.name: the English names for the months of the year;
  • pi: the ratio of the circumference of a circle to its diameter.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

data, DateTimeClasses.

Quotes for the parsing of character constants, NumericConstants for numeric constants.

Examples

# John Machin (1705) computed 100 decimals of pi :
pi - 4*(4*atan(1/5) - atan(1/239))

## months in English
month.name
## months in your current locale
format(ISOdate(2000, 1:12, 1), "%B")
format(ISOdate(2000, 1:12, 1), "%b")


R Project Contributors

Description

The R Who-is-who, describing who made significant contributions to the development of R.

Usage

contributors()


Control Flow

Description

These are the basic control-flow constructs of the R language. They function in much the same way as control statements in any Algol-like language.

Usage

if(cond) expr
if(cond) cons.expr  else  alt.expr

for(var in seq) expr
while(cond) expr
repeat expr
break
next

Arguments

cond | A length-one logical vector that is not NA. Conditions of length greater than one are accepted with a warning, but only the first element is used.
var | A syntactical name for a variable.
seq | An expression evaluating to a vector (including a list and an expression) or to a pairlist or NULL.
expr, cons.expr, alt.expr | An expression in a formal sense. This is either a simple expression or a so called compound expression, usually of the form { expr1 ; expr2 }.

Details

break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop. next halts the processing of the current iteration and advances the looping index. Both break and next apply only to the innermost of nested loops.

Note that it is a common mistake to forget to put braces ({ .. }) around your statements, e.g., after if(..) or for(....). In particular, you should not have a newline between } and else to avoid a syntax error in entering a if ... else construct at the keyboard or via source. For that reason, one (somewhat extreme) attitude of defensive programming is to always use braces, e.g., for if clauses.

The index seq in a for loop is evaluated at the start of the loop; changing it subsequently does not affect the loop. The variable var has the same type as seq, and is read-only: assigning to it does not alter seq. If seq is a factor (which is not strictly allowed) then its internal codes are used: the effect is that of as.integer not as.vector.

Value

if returns the value of the expression evaluated, or NULL if none was (which may happen if there is no else).
for, while and repeat return the value of the last expression evaluated (or NULL if none was), invisibly. for sets var to the last used element of seq, or to NULL if it was of length zero.
break and next have value NULL, although it would be strange to look for a return value.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

Syntax for the basic R syntax and operators, Paren for parentheses and braces; further, ifelse, switch.

Examples

for(i in 1:5) print(1:i)
for(n in c(2,5,10,20,50)) {
   x <- rnorm(n)
   cat(n,":", sum(x^2),"\n")
}


Management of .C argument conversion list

Description

These functions provide facilities to manage the extensible list of converters used to translate R objects to C pointers for use in .C calls. The number and a description of each element in the list can be retrieved. One can also query and set the activity status of individual elements, temporarily ignoring them. And one can remove individual elements.

Usage

getNumCConverters()
getCConverterDescriptions()
getCConverterStatus()
setCConverterStatus(id, status)
removeCConverter(id)

Arguments

id | either a number or a string identifying the element of interest in the converter list. A string is matched against the description strings for each element to identify the element. Integers are specified starting at 1 (rather than 0).
status | a logical value specifying whether the element is to be considered active (TRUE) or not (FALSE).

Details

The internal list of converters is potentially used when converting individual arguments in a .C call. If an argument has a non-trivial class attribute, we iterate over the list of converters looking for the first that “matches”. If we find a matching converter, we have it create the C-level pointer corresponding to the R object. When the call to the C routine is complete, we use the same converter for that argument to reverse the conversion and create an R object from the current value in the C pointer. This is done separately for all the arguments.

The functions documented here provide R user-level capabilities for investigating and managing the list of converters. There is currently no mechanism for adding an element to the converter list within the R language. This must be done in C code using the routine R_addToCConverter().

Value

getNumCConverters returns an integer giving the number of elements in the list, both active and inactive.
getCConverterDescriptions returns a character vector containing the description string of each element of the converter list.
getCConverterStatus returns a logical vector with a value for each element in the converter list. Each value indicates whether that converter is active (TRUE) or inactive (FALSE). The names of the elements are the description strings returned by getCConverterDescriptions.
setCConverterStatus returns the logical value indicating the activity status of the specified element before the call to change it took effect. This is TRUE for active and FALSE for inactive.
removeCConverter returns TRUE if an element in the converter list was identified and removed. In the case that no such element was found, an error occurs.

Author(s)

Duncan Temple Lang

References

http://developer.R-project.org/CObjectConversion.pdf

See Also

.C

Examples

getNumCConverters()
getCConverterDescriptions()
getCConverterStatus()
## Not run:
old <- setCConverterStatus(1, FALSE)

setCConverterStatus(1, old)
## End(Not run)
## Not run:
removeCConverter(1)
removeCConverter(getCConverterDescriptions()[1])
## End(Not run)


Copyrights of Files Used to Build R

Description

R is released under the ‘GNU Public License’: see license for details. The license describes your right to use R. Copyright is concerned with ownership of intellectual rights, and some of the software used has conditions that the copyright must be explicitly stated: see the Details section. We are grateful to these people and other contributors (see contributors) for the ability to use their work.

Details

The file ‘$R_HOME/COPYRIGHTS’ lists the copyrights in full detail.


Count the Number of Fields per Line

Description

count.fields counts the number of fields, as separated by sep, in each of the lines of file read.

Usage

count.fields(file, sep = "", quote = "\"'", skip = 0,
             blank.lines.skip = TRUE, comment.char = "#")

Arguments

file | a character string naming an ASCII data file, or a connection, which will be opened if necessary, and if so closed at the end of the function call.
sep | the field separator character. Values on each line of the file are separated by this character. By default, arbitrary amounts of whitespace can separate fields.
quote | the set of quoting characters
skip | the number of lines of the data file to skip before beginning to read data.
blank.lines.skip | logical: if TRUE blank lines in the input are ignored.
comment.char | character: a character vector of length one containing a single character or an empty string.

Details

This used to be used by read.table and can still be useful in discovering problems in reading a file by that function.

For the handling of comments, see scan.

Value

A vector with the numbers of fields found.

See Also

read.table

Examples

cat("NAME", "1:John", "2:Paul", file = "foo", sep = "\n")
count.fields("foo", sep = ":")
unlink("foo")


Matrix Crossproduct

Description

Given matrices x and y as arguments, return a matrix cross-product. This is formally equivalent to (but faster than) the call t(x) %*% y (crossprod) or x %*% t(y) (tcrossprod).

Usage

crossprod(x, y = NULL)

tcrossprod(x, y = NULL)

Arguments

x, y matrices: y = NULL is taken to be the same matrix as x. Vectors are promoted to single-column matrices.

Note

When x or y are not matrices, they are treated as column or row matrices, but their names are usually not promoted to dimnames. Hence, currently, the last example has empty dimnames.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

%*% and outer product %o%.

Examples

(z <- crossprod(1:4))    # = sum(1 + 2^2 + 3^2 + 4^2)
drop(z)                  # scalar
x <- 1:4; names(x) <- letters[1:4]; x
tcrossprod(as.matrix(x)) # is
identical(tcrossprod(as.matrix(x)),
          crossprod(t(x)))
tcrossprod(x)            # no dimnames


Report Information on C Stack Size and Usage

Description

Report information on the C stack size and usage (if available).

Usage

Cstack_info()

Details

On most platforms, C stack information is recorded when R is initialized and used for stack-checking. If this information is unavailable, the size will be returned as NA, and stack-checking is not performed.

The information on the stack base address is thought to be accurate on Windows, Linux and FreeBSD (including MacOS X), but a heuristic is used on other platforms. Because this might be slightly inaccurate, the current usage could be estimated as negative. (The heuristic is not used on embedded uses of R on platforms where the stack base is not thought to be accurate.)

Value

An integer vector. This has named elements

size | The size of the stack (in bytes), or NA if unknown.
current | The estimated current usage (in bytes), possibly NA.
direction | 1 (stack grows down, the usual case) or -1 (stack grows up).
eval_depth | The current evaluation depth (including two calls for the call to Cstack_info).

Examples

Cstack_info()


Cumulative Sums, Products, and Extremes

cumsum(base) R Documentation

Cumulative Sums Products and Extremes

Description

Returns a vector whose elements are the cumulative sums, products, minima or maxima of the elements of the argument.

Usage

cumsum(x)
cumprod(x)
cummax(x)
cummin(x)

Arguments

x a numeric or complex (not cummin or cummax) object, or an object that can be coerced to one of these.

Details

These are generic functions: methods can be defined for them individually or via the Math group generic.

Value

A vector of the same length and type as x (after coercion), except that cumprod returns a numeric vector for integer input (for consistency with *). Names are preserved.
An NA value in x causes the corresponding and following elements of the return value to be NA, as does integer overflow in cumsum (with a warning).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole. (cumsum only.)

Examples

cumsum(1:10)
cumprod(1:10)
cummin(c(3:1, 2:0, 4:2))
cummax(c(3:1, 2:0, 4:2))


Convert Numeric to Factor

Description

cut divides the range of x into intervals and codes the values in x according to which interval they fall. The leftmost interval corresponds to level one, the next leftmost to level two and so on.

Usage

cut(x, ...)

## Default S3 method:
cut(x, breaks, labels = NULL,
    include.lowest = FALSE, right = TRUE, dig.lab = 3, ...)

Arguments

x | a numeric vector which is to be converted to a factor by cutting.
breaks | either a numeric vector of cut points or number giving the number of intervals which x is to be cut into.
labels | labels for the levels of the resulting category. By default, labels are constructed using "(a,b]" interval notation. If labels = FALSE, simple integer codes are returned instead of a factor.
include.lowest | logical, indicating if an ‘x[i]’ equal to the lowest (or highest, for right = FALSE) ‘breaks’ value should be included.
right | logical, indicating if the intervals should be closed on the right (and open on the left) or vice versa.
dig.lab | integer which is used when labels are not given. It determines the number of digits used in formatting the break numbers.
... | further arguments passed to or from other methods.

Details

If a labels parameter is specified, its values are used to name the factor levels. If none is specified, the factor level labels are constructed as "(b1, b2]", "(b2, b3]" etc. for right = TRUE and as "[b1, b2)", ... if right = FALSE. In this case, dig.lab indicates the minimum number of digits should be used in formatting the numbers b1, b2, .... A larger value (up to 12) will be used if needed to distinguish between any pair of endpoints: if this fails labels such as "Range3" will be used.

Value

A factor is returned, unless labels = FALSE which results in the mere integer level codes.

Note

Instead of table(cut(x, br)), hist(x, br, plot = FALSE) is more efficient and less memory hungry. Instead of cut(*, labels = FALSE), findInterval() is more efficient.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

split for splitting a variable according to a group factor; factor, tabulate, table, findInterval().

Examples

Z <- rnorm(10000)
table(cut(Z, br = -6:6))
sum(table(cut(Z, br = -6:6, labels=FALSE)))
sum(   hist  (Z, br = -6:6, plot=FALSE)$counts)

cut(rep(1,5),4)#-- dummy
tx0 <- c(9, 4, 6, 5, 3, 10, 5, 3, 5)
x <- rep(0:8, tx0)
stopifnot(table(x) == tx0)

table( cut(x, b = 8))
table( cut(x, br = 3*(-2:5)))
table( cut(x, br = 3*(-2:5), right = FALSE))

##--- some values OUTSIDE the breaks :
table(cx  <- cut(x, br = 2*(0:4)))
table(cxl <- cut(x, br = 2*(0:4), right = FALSE))
which(is.na(cx));  x[is.na(cx)]  #-- the first 9  values  0
which(is.na(cxl)); x[is.na(cxl)] #-- the last  5  values  8

## Label construction:
y <- rnorm(100)
table(cut(y, breaks = pi/3*(-3:3)))
table(cut(y, breaks = pi/3*(-3:3), dig.lab=4))

table(cut(y, breaks =  1*(-3:3), dig.lab=4))
# extra digits don't "harm" here
table(cut(y, breaks =  1*(-3:3), right = FALSE))
#- the same, since no exact INT!

## sometimes the default dig.lab is not enough to be avoid confusion:
aaa <- c(1,2,3,4,5,2,3,4,5,6,7)
cut(aaa, 3)
cut(aaa, 3, dig.lab=4)


Convert a Date or Date-Time Object to a Factor

Description

Method for cut applied to date-time objects.

Usage

## S3 method for class 'POSIXt':
cut(x, breaks, labels = NULL, start.on.monday = TRUE,
    right = FALSE, ...)

## S3 method for class 'Date':
cut(x, breaks, labels = NULL, start.on.monday = TRUE,
    right = FALSE, ...)

Arguments

x | an object inheriting from class "POSIXt" or "Date".
breaks | a vector of cut points or number giving the number of intervals which x is to be cut into or an interval specification, one of "sec", "min", "hour", "day", "DSTday", "week", "month" or "year", optionally preceded by an integer and a space, or followed by "s". For "Date" objects only "day", "week", "month" and "year" are allowed.
labels | labels for the levels of the resulting category. By default, labels are constructed from the left-hand end of the intervals (which are include for the default value of right). If labels = FALSE, simple integer codes are returned instead of a factor.
start.on.monday | logical. If breaks = "weeks", should the week start on Mondays or Sundays?
right, ... | arguments to be passed to or from other methods.

Details

Using both right = TRUE and include.lowest = TRUE will include both ends of the range of dates.

Value

A factor is returned, unless labels = FALSE which returns the integer level codes.

See Also

seq.POSIXt, seq.Date, cut

Examples

## random dates in a 10-week period
cut(ISOdate(2001, 1, 1) + 70*86400*runif(100), "weeks")
cut(as.Date("2001/1/1") + 70*runif(100), "weeks")


Object Classes

Description

Determine the class of an arbitrary R object.

Usage

data.class(x)

Arguments

x an R object.

Value

character string giving the “class” of x.
The “class” is the (first element) of the class attribute if this is non-NULL, or inferred from the object's dim attribute if this is non-NULL, or mode(x).
Simply speaking, data.class(x) returns what is typically useful for method dispatching. (Or, what the basic creator functions already and maybe eventually all will attach as a class attribute.)

Note

For compatibility reasons, there is one exception to the rule above: When x is integer, the result of data.class(x) is "numeric" even when x is classed.

See Also

class

Examples

x <- LETTERS
data.class(factor(x))                 # has a class attribute
data.class(matrix(x, nc = 13))        # has a dim attribute
data.class(list(x))                   # the same as mode(x)
data.class(x)                         # the same as mode(x)

stopifnot(data.class(1:2) == "numeric")# compatibility "rule"


Data Frames

Description

This function creates data frames, tightly coupled collections of variables which share many of the properties of matrices and of lists, used as the fundamental data structure by most of R's modeling software.

Usage

data.frame(..., row.names = NULL, check.rows = FALSE,
           check.names = TRUE,
           stringsAsFactors = default.stringsAsFactors())

default.stringsAsFactors()

Arguments

... | these arguments are of either the form value or tag = value. Component names are created based on the tag (if present) or the deparsed argument itself.
row.names | NULL or a single integer or character string specifying a column to be used as row names, or a character or integer vector giving the row names for the data frame.
check.rows | if TRUE then the rows are checked for consistency of length and names.
check.names | logical. If TRUE then the names of the variables in the data frame are checked to ensure that they are syntactically valid variable names and are not duplicated. If necessary they are adjusted (by make.names) so that they are.
stringsAsFactors | logical: should character vectors be converted to factors?

Details

A data frame is a list of variables of the same length with unique row names, given class "data.frame".

data.frame converts each of its arguments to a data frame by calling as.data.frame(optional=TRUE). As that is a generic function, methods can be written to change the behaviour of arguments according to their classes: R comes with many such methods. Character variables passed to data.frame are converted to factor columns unless protected by I. If a list or data frame or matrix is passed to data.frame it is as if each component or column had been passed as a separate argument.

Objects passed to data.frame should have the same number of rows, but atomic vectors, factors and character vectors protected by I will be recycled a whole number of times if necessary.

If row names are not supplied in the call to data.frame, the row names are taken from the first component that has suitable names, for example a named vector or a matrix with rownames or a data frame. (If that component is subsequently recycled, the names are discarded with a warning.) If row.names was supplied as NULL or no suitable component was found the row names are the integer sequence starting at one.

If row names are supplied of length one and the data frame has a single row, the row.names is taken to specify the row names and not a column (by name or number).

Names are removed from vector inputs not protected by I.

default.stringsAsFactors is a utility that takes getOption("stringsAsFactors") and ensures the result is TRUE or FALSE.

Value

A data frame, a matrix-like structure whose columns may be of differing types (numeric, logical, factor and character and so on).

Note

In versions of R prior to 2.4.0 row.names had to be character: to ensure compatibility with earlier versions of R, supply a character vector as the row.names argument.

References

Chambers, J. M. (1992) Data for models. Chapter 3 of Statistical Models in S eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole.

See Also

I, plot.data.frame, print.data.frame, row.names, names (for the column names), [.data.frame for subsetting methods, Math.data.frame etc, about Group methods for data.frames; read.table, make.names.

Examples

L3 <- LETTERS[1:3]
(d <- data.frame(cbind(x=1, y=1:10), fac=sample(L3, 10, repl=TRUE)))

## The same with automatic column names:
data.frame(cbind(  1,   1:10),     sample(L3, 10, repl=TRUE))

is.data.frame(d)

## do not convert to factor, using I() :
(dd <- cbind(d, char = I(letters[1:10])))
rbind(class=sapply(dd, class), mode=sapply(dd, mode))

stopifnot(1:10 == row.names(d))# {coercion}

(d0  <- d[, FALSE]) # NULL data frame with 10 rows
(d.0 <- d[FALSE, ]) # <0 rows> data frame  (3 cols)
(d00 <- d0[FALSE,])  # NULL data frame with 0 rows


Data Frame to Numeric Matrix

Description

Return the matrix obtained by converting all the variables in a data frame to numeric mode and then binding them together as the columns of a matrix. Factors and ordered factors are replaced by their internal codes.

Usage

data.matrix(frame)

Arguments

frame a data frame whose components are logical vectors, factors or numeric vectors.

Details

Supplying a data frame with columns which are not numeric, factor or logical is an error. A warning is given if any non-factor column has a class, as then information can be lost.

Value

If frame is a data frame, a numeric matrix of the same dimensions as frame, with dimnames taken from the row.names and names.
Otherwise, the result of as.matrix.

References

Chambers, J. M. (1992) Data for models. Chapter 3 of Statistical Models in S eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole.

See Also

as.matrix, data.frame, matrix.

Examples

DF <- data.frame(a=1:3, b=letters[10:12],
                 c=seq(as.Date("2004-01-01"), by = "week", len = 3),
                 stringsAsFactors = TRUE)
data.matrix(DF[1:2])
data.matrix(DF) # gives a warning and quotes dates as #days since 1970.


Data Frame Auxiliary Functions

Description

Auxiliary functions for use with data frames.

Usage

xpdrows.data.frame(x, old.rows, new.rows)

Arguments

x | object of class data.frame.
old.rows, new.rows | row names for old and new rows.

Details

xpdrows.data.frame is an auxiliary function which expands the rows of a data frame. It is used by the data frame methods of [<- and [[<- (which perform subscripted assignments on a data frame), and not intended to be called directly.

See Also

[.data.frame


System Date and Time

Description

Returns a character string of the current system date and time.

Usage

date()

Value

The string has the form "Fri Aug 20 11:11:00 1999", i.e., length 24, since it relies on POSIX's ctime ensuring the above fixed format. Timezone and Daylight Saving Time are taken account of, but not indicated in the result.
The day and month abbreviations are always in English, irrespective of locale.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

Sys.time; Date and DateTimeClasses for objects representing date and time.

Examples

(d <- date())
nchar(d) == 24

## something similar in the current locale
format(Sys.time(), "%a %b %d %H:%M:%S %Y")


Date Class

Description

Description of the class "Date" representing calendar dates.

Usage

## S3 method for class 'Date':
summary(object, digits = 12, ...)

Arguments

object | An object summarized.
digits | Number of significant digits for the computations.
... | Further arguments to be passed from or to other methods.

Details

Dates are represented as the number of days since 1970-01-01, with negative values for earlier dates. They are always printed following the rules of the current Gregorian calendar, even though that calendar was not in use long ago (it was adopted in 1752 in Great Britain and its colonies).

It is intended that the date should be an integer, but this is not enforced in the internal representation. Fractional days will be ignored when printing. It is possible to produce fractional days via the mean method or by adding or subtracting (see Ops.Date).

See Also

Sys.Date for the current date.

Ops.Date for operators on "Date" objects.

format.Date for conversion to and from character strings.

plot.Date and hist.Date for plotting.

weekdays for convenience extraction functions.

seq.Date, cut.Date, round.Date for utility operations.

DateTimeClasses for date-time classes.

Examples

(today <- Sys.Date())
format(today, "%d %b %Y")  # with month as a word
(tenweeks <- seq(today, len=10, by="1 week")) # next ten weeks
weekdays(today)
months(tenweeks)
as.Date(.leap.seconds)


Date-Time Classes

Description

Description of the classes "POSIXlt" and "POSIXct" representing calendar dates and times (to the nearest second).

Usage

## S3 method for class 'POSIXct':
print(x, ...)

## S3 method for class 'POSIXct':
summary(object, digits = 15, ...)

time + z
time - z
time1 lop time2

Arguments

x, object | An object to be printed or summarized from one of the date-time classes.
digits | Number of significant digits for the computations: should be high enough to represent the least important time unit exactly.
... | Further arguments to be passed from or to other methods.
time | date-time objects
time1, time2 | date-time objects or character vectors. (Character vectors are converted by as.POSIXct.
z | a numeric vector (in seconds) or an object of class "difftime".
lop | One of ==, !=, <, <=, > or >=.

Details

There are two basic classes of date/times. Class "POSIXct" represents the (signed) number of seconds since the beginning of 1970 as a numeric vector. Class "POSIXlt" is a named list of vectors representing

sec
0–61: seconds
min
0–59: minutes
hour
0–23: hours
mday
1–31: day of the month
mon
0–11: months after the first of the year.
year
Years since 1900.
wday
0–6 day of the week, starting on Sunday.
yday
0–365: day of the year.
isdst
Daylight savings time flag. Positive if in force, zero if not, negative if unknown.

The classes correspond to the ANSI C constructs of “calendar time” (the time\_t data type) and “local time” (or broken-down time, the struct tm data type), from which they also inherit their names.

"POSIXct" is more convenient for including in data frames, and "POSIXlt" is closer to human-readable forms. A virtual class "POSIXt" inherits from both of the classes: it is used to allow operations such as subtraction to mix the two classes.

Logical comparisons and limited arithmetic are available for both classes. One can add or subtract a number of seconds or a difftime object from a date-time object, but not add two date-time objects. Subtraction of two date-time objects is equivalent to using difftime. Be aware that "POSIXlt" objects will be interpreted as being in the current timezone for these operations, unless a timezone has been specified.

"POSIXlt" objects will often have an attribute "tzone", a character vector of length 3 giving the timezone name from the TZ environment variable and the names of the base timezone and the alternate (daylight-saving) timezone. Sometimes this may just be of length one, giving the timezone name.

"POSIXct" objects may also have an attribute "tzone", a character vector of length one. If set, it will determine how the object is converted to class "POSIXlt" and in particular how it is printed. This is usually desirable, but if you want to specify an object in a particular timezone but to be printed in the current timezone you may want to remove the "tzone" attribute (e.g. by c(x)).

Unfortunately, the conversion is complicated by the operation of time zones and leap seconds (23 days have been 86401 seconds long so far: the times of the extra seconds are in the object .leap.seconds). The details of this are entrusted to the OS services where possible. This will usually cover the period 1970–2037, and on Unix machines back to 1902 (when time zones were in their infancy). Outside those ranges we use our own C code. This uses the offset from GMT in use in the timezone in one of 1970 to 1978 (chosen so that the likely DST transition days are Sundays), and uses the alternate (daylight-saving) timezone only if isdst is positive.

It seems that some systems use leap seconds but most do not. This is detected and corrected for at build time, so all "POSIXct" times used by R do not include leap seconds. (Conceivably this could be wrong if the system has changed since build time, just possibly by changing locales.)

Using c on "POSIXlt" objects converts them to the current time zone.

Sub-section Accuracy

Classes "POSIXct" and "POSIXlt" are able to express fractions of a second. (Conversion of fractions between the two forms may not be exact, but will have better than microsecond accuracy.)

Fractional seconds are printed only if options("digits.secs") is set: see strftime.

Warning

Some Unix-like systems (especially Linux ones) do not have "TZ" set, yet have internal code that expects it (as does POSIX). We have tried to work around this, but if you get unexpected results try setting "TZ". See as.POSIXlt for valid settings.

See Also

Dates for dates without times.

as.POSIXct and as.POSIXlt for conversion between the classes.

strptime for conversion to and from character representations.

Sys.time for clock time as a "POSIXct" object.

difftime for time intervals.

cut.POSIXt, seq.POSIXt, round.POSIXt and trunc.POSIXt for methods for these classes.

weekdays.POSIXt for convenience extraction functions.

Examples

(z <- Sys.time())             # the current date, as class "POSIXct"

Sys.time() - 3600             # an hour ago

as.POSIXlt(Sys.time(), "GMT") # the current time in GMT
format(.leap.seconds)         # all 23 leapseconds in your timezone
print(.leap.seconds, tz="PST8PDT")  # and in Seattle's


Read and Write Data in DCF Format

Description

Reads or writes an R object from/to a file in Debian Control File format.

Usage

read.dcf(file, fields=NULL)
write.dcf(x, file = "", append = FALSE,
          indent = 0.1 * getOption("width"),
          width = 0.9 * getOption("width"))

Arguments

file | either a character string naming a file or a connection. "" indicates output to the console. For read.dcf this can name a gzip-compressed file.
fields | Fields to read from the DCF file. Default is to read all fields.
x | the object to be written, typically a data frame. If not, it is attempted to coerce x to a data frame.
append | logical. If TRUE, the output is appended to the file. If FALSE, any existing file of the name is destroyed.
indent | a positive integer specifying the indentation for continuation lines in output entries.
width | a positive integer giving the target column for wrapping lines in the output.

Details

DCF is a simple format for storing databases in plain text files that can easily be directly read and written by humans. DCF is used in various places to store R system information, like descriptions and contents of packages.

The DCF rules as implemented in R are:

  1. A database consists of one or more records, each with one or more named fields. Not every record must contain each field, a field may appear only once in a record.
  2. Regular lines start with a non-whitespace character.
  3. Regular lines are of form tag:value, i.e., have a name tag and a value for the field, separated by : (only the first : counts). The value can be empty (=whitespace only).
  4. Lines starting with whitespace are continuation lines (to the preceding field) if at least one character in the line is non-whitespace.
  5. Records are separated by one or more empty (=whitespace only) lines.

read.dcf returns a character matrix with one line per record and one column per field. Leading and trailing whitespace of field values is ignored. If a tag name is specified, but the corresponding value is empty, then an empty string of length 0 is returned. If the tag name of a fields is never used in a record, then NA is returned. If there are multiple records with the same tag name, the last one encountered is returned. Malformed lines are ignored (with a warning).

See Also

write.table.

Examples

## Create a reduced version of the 'CONTENTS' file in package 'splines'
x <- read.dcf(file = system.file("CONTENTS", package = "splines"),
              fields = c("Entry", "Description"))
write.dcf(x)


Debug a Function

Description

Set or unset the debugging flag on a function.

Usage

debug(fun)
undebug(fun)

Arguments

fun any interpreted R function.

Details

When a function flagged for debugging is entered, normal execution is suspended and the body of function is executed one statement at a time. A new browser context is initiated for each step (and the previous one destroyed).

At the debug prompt the user can enter commands or R expressions. The commands are

n
(or just return). Advance to the next step.
c
continue to the end of the current context: e.g. to the end of the loop if within a loop or to the end of the function.
cont
synonym for c.
where
print a stack trace of all active function calls.
Q
exit the browser and the current evaluation and return to the top-level prompt.
(Leading and trailing whitespace is ignored, except for return).

Anything else entered at the debug prompt is interpreted as an R expression to be evaluated in the calling environment: in particular typing an object name will cause the object to be printed, and ls() lists the objects in the calling frame. (If you want to look at an object with a name such as n, print it explicitly.)

If a function is defined inside a function, single-step though to the end of its definition, and then call debug on its name.

In order to debug S4 methods (see Methods), you need to use trace, typically calling browser, e.g., as
trace("plot", browser, exit=browser, signature = c("track", "missing"))

See Also

browser, trace; traceback to see the stack after an Error: ... message; recover for another debugging approach.


Marking Objects as Defunct

Description

When an object is removed from R it should be replaced by a call to .Defunct.

Usage

.Defunct(new, package = NULL)

Arguments

new | character string: A suggestion for a replacement function.
package | character string: The package to be used when suggesting where the defunct function might be listed.

Details

.Defunct is called from defunct functions. Functions should be listed in help("pkg-defunct") for an appropriate pkg, including base.

See Also

Deprecated.

base-defunct and so on which list the defunct functions in the packages.


Delay Evaluation

Description

delayedAssign creates a promise to evaluate the given expression if its value is requested. This provides direct access to the lazy evaluation mechanism used by R for the evaluation of (interpreted) functions.

Usage

delayedAssign(x, value, eval.env = parent.frame(1),
              assign.env = parent.frame(1))

Arguments

x | a variable name (given as a quoted string in the function call)
value | an expression to be assigned to x
eval.env | an environment in which to evaluate value
assign.env | an environment in which to assign x

Details

Both eval.env and assign.env default to the currently active environment.

The expression assigned to a promise by delayedAssign will not be evaluated until it is eventually ``forced''. This happens when the variable is first accessed.

When the promise is eventually forced, it is evaluated within the environment specified by eval.env (whose contents may have changed in the meantime). After that, the value is fixed and the expression will not be evaluated again.

This function is meant to replace the delay() function, to make it more difficult for R code to see ``naked'' promises.

Value

This function is invoked for its side effect, which is assigning a promise to evaluate value to the variable x.

See Also

substitute, to see the expression associated with a promise.

Examples

msg <- "old"
delayedAssign("x", msg)
msg <- "new!"
x #- new!
substitute(x) #- msg

delayedAssign("x", {
    for(i in 1:3)
        cat("yippee!\n")
    10
})

x^2 #- yippee
x^2 #- simple number

e <- (function(x, y = 1, z) environment())(1+2, "y", {cat(" HO! "); pi+2})
(le <- as.list(e)) # evaluates the promises


Expression Deparsing

Description

Turn unevaluated expressions into character strings.

Usage

deparse(expr, width.cutoff = 60,
        backtick = mode(expr) %in% c("call", "expression", "("),
        control = "showAttributes")

Arguments

expr | any R expression.
width.cutoff | integer in [20, 500] determining the cutoff at which line-breaking is tried.
backtick | logical indicating whether symbolic names should be enclosed in backticks if they do not follow the standard syntax.
control | character vector of deparsing options. See .deparseOpts.

Details

This function turns unevaluated expressions (where “expression” is taken in a wider sense than the strict concept of a vector of mode "expression" used in expression) into character strings (a kind of inverse parse).

A typical use of this is to create informative labels for data sets and plots. The example shows a simple use of this facility. It uses the functions deparse and substitute to create labels for a plot which are character string versions of the actual arguments to the function myplot.

The default for the backtick option is not to quote single symbols but only composite expressions. This is a compromise to avoid breaking existing code.

Using control = "all" comes closest to making deparse() an inverse of parse(). However, not all objects are deparseable even with this option and a warning will be issued if the function recognizes that it is being asked to do the impossible.

Note

To avoid the risk of a source attribute out of sync with the actual function definition, the source attribute of a function will never be deparsed as an attribute.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

substitute, parse, expression.

Quotes for quoting conventions, including backticks.

Examples

require(stats)
deparse(args(lm))
deparse(args(lm), width = 500)
myplot <-
function(x, y) {
    plot(x, y, xlab=deparse(substitute(x)),
        ylab=deparse(substitute(y)))
}
e <- quote(`foo bar`)
deparse(e)
deparse(e, backtick=TRUE)
e <- quote(`foo bar`+1)
deparse(e)
deparse(e, control = "all")


Options for Expression Deparsing

Description

Process the deparsing options for deparse, dput and dump.

Usage

.deparseOpts(control)

Arguments

control character vector of deparsing options.

Details

This is called by deparse, dput and dump to process their control argument.

The control argument is a vector containing zero or more of the following strings. Partial string matching is used.

keepInteger
Surround integer vectors by as.integer(), so they are not converted to floating point when re-parsed.
quoteExpressions
Surround expressions with quote(), so they are not evaluated when re-parsed.
showAttributes
If the object has attributes (other than a source attribute), use structure() to display them as well as the object value. This is the default for deparse and dput.
useSource
If the object has a source attribute, display that instead of deparsing the object. Currently only applies to function definitions.
warnIncomplete
Some exotic objects such as environments, external pointers, etc. can not be deparsed properly. This option causes a warning to be issued if any of those may give problems.
all
An abbreviated way to specify all of the options listed above. May not be used with other options. This is the default for dump.
delayPromises
Deparse promises in the form <promise: expression> rather than evaluating them. The value and the environment of the promise will not be shown and the deparsed code cannot be sourced.

For the most readable (but perhaps incomplete) display, use control = NULL. This displays the object's value, but not its attributes. The default is to display the attributes as well, but not to use any of the other options to make the result parseable.

Using control = "all" comes closest to making deparse() an inverse of parse(). However, not all objects are deparseable even with this option. A warning will be issued if the function recognizes that it is being asked to do the impossible.

Value

A numerical value corresponding to the options selected.


Marking Objects as Deprecated

Description

When an object is about removed from R it is first deprecated and should include a call to .Deprecated.

Usage

.Deprecated(new, package=NULL)

Arguments

new | character string: A suggestion for a replacement function.
package | character string: The package to be used when suggesting where the deprecated function might be listed.

Details

.Deprecated("<new name>") is called from deprecated functions. The original help page for these functions is often available at help("oldName-deprecated") (note the quotes). Functions should be listed in help("pkg-deprecated") for an appropriate pkg, including base.

See Also

Defunct

base-deprecated and so on which list the deprecated functions in the packages.


Calculate the Determinant of a Matrix

Description

det calculates the determinant of a matrix. determinant is a generic function that returns separately the modulus of the determinant, optionally on the logarithm scale, and the sign of the determinant.

Usage

det(x, ...)
determinant(x, logarithm = TRUE, ...)

Arguments

x | numeric matrix.
logarithm | logical; if TRUE (default) return the logarithm of the modulus of the determinant.
... | Optional arguments. At present none are used. Previous versions of det allowed an optional method argument. This argument will be ignored but will not produce an error.

Details

The determinant function uses an LU decomposition and the det function is simply a wrapper around a call to determinant.

Often, computing the determinant is not what you should be doing to solve a given problem.

Value

For det, the determinant of x. For determinant, a list with components

modulus | a numeric value. The modulus (absolute value) of the determinant if logarithm is FALSE; otherwise the logarithm of the modulus.
sign | integer; either +1 or -1 according to whether the determinant is positive or negative.

Examples

(x <- matrix(1:4, ncol=2))
unlist(determinant(x))
det(x)

det(print(cbind(1,1:3,c(2,0,1))))


Detach Objects from the Search Path

Description

Detach a database, i.e., remove it from the search() path of available R objects. Usually, this is either a data.frame which has been attached or a package which was required previously.

Usage

detach(name, pos = 2, version)

Arguments

name | The object to detach. Defaults to search()[pos]. This can be an unquoted name or a character string but not a character vector. If a number is supplied this is taken as pos.
pos | Index position in search() of database to detach. When name is a number, pos = name is used.
version | A character string denoting a version number of the package to be removed. This should be used only with a versioned installation of the package: see library.

Details

This most commonly used with a single number argument referring to a position on the search list, and can also be used with a unquoted or quoted name of an item on the search list such as package:tools.

When a package have been loaded with an explicit version number it can be detached using the name shown by search or by supplying name and version: see the examples.

Value

The attached database is returned invisibly, either as data.frame or as list.

Note

You cannot detach either the workspace (position 1) or the base package (the last item in the search list).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

attach, library, search, objects.

Examples

require(splines)#package
detach(package:splines)
## could equally well use detach("package:splines")
## but NOT  pkg <- "package:splines"; detach(pkg)
## Instead, use
library(splines)
pkg <- "package:splines"
detach(pos = match(pkg, search()))

## careful: do not do this unless 'splines' is not already loaded.
library(splines)
detach(2)# 'pos' used for 'name'

## an example of the name argument to attach
## and of detaching a database named by a character vector
attach_and_detach <- function(db, pos=2)
{
   name <- deparse(substitute(db))
   attach(db, pos=pos, name=name)
   print(search()[pos])
   eval(substitute(detach(n), list(n=name)))
}
attach_and_detach(women, pos=3)

## Not run:
## Using a versioned install
library(ash, version="1.0-9")  # or perhaps just library(ash)
# then one of
detach("package:ash", version="1.0-9")
# or
detach("package:ash_1.0-9")
## End(Not run)


Lists of Open Graphics Devices

Description

A list of the names of the open graphics devices is stored in .Devices. The name of the active device is stored in .Device.


Matrix Diagonals

Description

Extract or replace the diagonal of a matrix, or construct a diagonal matrix.

Usage

diag(x = 1, nrow, ncol = n)
diag(x) <- value

Arguments

x | a matrix, vector or 1D array.
nrow, ncol | Optional dimensions for the result.
value | either a single value or a vector of length equal to that of the current diagonal. Should be of a mode which can be coerced to that of x.

Value

If x is a matrix then diag(x) returns the diagonal of x. The resulting vector will have names if the matrix x has matching column and row names.
If x is a vector (or 1D array) of length two or more, then diag(x) returns a diagonal matrix whose diagonal is x.
If x is a vector of length one then diag(x) returns an identity matrix of order the nearest integer to x. The dimension of the returned matrix can be specified by nrow and ncol (the default is square).
The replacement form sets the diagonal of the matrix x to the given value(s).

Note

Using diag(x) can have unexpected effects if x is a vector that could be of length one. Use diag(x, nrow = length(x)) for consistent behaviour.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

upper.tri, lower.tri, matrix.

Examples

require(stats)
dim(diag(3))
diag(10,3,4) # guess what?
all(diag(1:3) == {m <- matrix(0,3,3); diag(m) <- 1:3; m})

diag(var(M <- cbind(X=1:5, Y=rnorm(5))))#-> vector with names "X" and "Y"
rownames(M) <- c(colnames(M),rep("",3));
M; diag(M) #  named as well


Lagged Differences

Description

Returns suitably lagged and iterated differences.

Usage

diff(x, ...)

## Default S3 method:
diff(x, lag = 1, differences = 1, ...)

## S3 method for class 'POSIXt':
diff(x, lag = 1, differences = 1, ...)

## S3 method for class 'Date':
diff(x, lag = 1, differences = 1, ...)

Arguments

x | a numeric vector or matrix containing the values to be differenced.
lag | an integer indicating which lag to use.
differences | an integer indicating the order of the difference.
... | further arguments to be passed to or from methods.

Details

diff is a generic function with a default method and ones for classes "ts", "POSIXt" and "Date".

NA's propagate.

Value

If x is a vector of length n and differences=1, then the computed result is equal to the successive differences x[(1+lag):n] - x[1:(n-lag)].
If difference is larger than one this algorithm is applied recursively to x. Note that the returned value is a vector which is shorter than x.
If x is a matrix then the difference operations are carried out on each column separately.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

diff.ts, diffinv.

Examples

diff(1:10, 2)
diff(1:10, 2, 2)
x <- cumsum(cumsum(1:10))
diff(x, lag = 2)
diff(x, differences = 2)

diff(.leap.seconds)


Time Intervals

Description

Create, print and round time intervals.

Usage

time1 - time2

difftime(time1, time2, tz = "",
         units = c("auto", "secs", "mins", "hours", "days", "weeks"))

as.difftime(tim, format = "%X")

## S3 method for class 'difftime':
round(x, digits = 0)

Arguments

time1, time2 | date-time or date objects.
tz | a timezone specification to be used for the conversion. System-specific, but "" is the current time zone, and "GMT" is UTC.
units | character. Units in which the results are desired. Can be abbreviated.
tim | character string specifying a time interval.
format | character specifying the format of tim: see strptime. The default is a locale-specific time format.
x | an object inheriting from class "difftime".
digits | integer. Number of significant digits to retain.

Details

Function difftime takes a difference of two date/time objects and returns an object of class "difftime" with an attribute indicating the units. There is a round method for objects of this class, as well as methods for the group-generic (see Ops) logical and arithmetic operations.

If units = "auto", a suitable set of units is chosen, the largest possible (excluding "weeks") in which all the absolute differences are greater than one.

Subtraction of date-time objects gives an object of this class, by calling difftime with units="auto". Alternatively, as.difftime() works on character-coded time intervals.

Limited arithmetic is available on "difftime" objects: they can be added or subtracted, and multiplied or divided by a numeric vector. In addition, adding or subtracting a numeric vector implicitly converts the numeric vector to a "difftime" object with the same units as the "difftime" object.

See Also

DateTimeClasses.

Examples

(z <- Sys.time() - 3600)
Sys.time() - z                # just over 3600 seconds.

## time interval between releases of 1.2.2 and 1.2.3.
ISOdate(2001, 4, 26) - ISOdate(2001, 2, 26)

as.difftime(c("0:3:20", "11:23:15"))
as.difftime(c("3:20", "23:15", "2:"), format= "%H:%M")# 3rd gives NA


Dimensions of an Object

Description

Retrieve or set the dimension of an object.

Usage

dim(x)
dim(x) <- value

Arguments

x | an R object, for example a matrix, array or data frame.
value | For the default method, either NULL or a numeric vector which coerced to integer (by truncation).

Details

The functions dim and dim<- are generic.

dim has a method for data.frames, which returns the length of the row.names attribute of x and the length of x (the numbers of “rows” and “columns”).

Value

For an array (and hence in particular, for a matrix) dim retrieves the dim attribute of the object. It is NULL or a vector of mode integer.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

ncol, nrow and dimnames.

Examples

x <- 1:12 ; dim(x) <- c(3,4)
x

# simple versions of nrow and ncol could be defined as follows
nrow0 <- function(x) dim(x)[1]
ncol0 <- function(x) dim(x)[2]


Dimnames of an Object

Description

Retrieve or set the dimnames of an object.

Usage

dimnames(x)
dimnames(x) <- value

Arguments

x | an R object, for example a matrix, array or data frame.
value | a possible value for dimnames(x): see “Value”.

Details

The functions dimnames and dimnames<- are generic.

For an array (and hence in particular, for a matrix), they retrieve or set the dimnames attribute (see attributes) of the object. A list value can have names, and these will be used to label the dimensions of the array where appropriate.

The replacement method for arrays/matrices coerces vector and factor elements of value to character, but does not dispatch methods for as.character. It coerces zero-length elements to NULL.

Both have methods for data frames. The dimnames of a data frame are its row.names and its names. For the replacement method each component of value will be coerced by as.character.

For a 1D matrix the names are the same thing as the (only) component of the dimnames.

Value

The dimnames of a matrix or array can be NULL or a list of the same length as dim(x). If a list, its components are either NULL or a character vector with positive length of the appropriate dimension of x.
For the "data.frame" method both dimnames are character vectors, and the rownames must contain no duplicates nor missing values.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

rownames, colnames; array, matrix, data.frame.

Examples

## simple versions of rownames and colnames
## could be defined as follows
rownames0 <- function(x) dimnames(x)[[1]]
colnames0 <- function(x) dimnames(x)[[2]]


Execute a Function Call

Description

do.call constructs and executes a function call from a name or a function and a list of arguments to be passed to it.

Usage

do.call(what, args, quote = FALSE, envir = parent.frame())

Arguments

what | either a function or a character string naming the function to be called.
args | a list of arguments to the function call. The names attribute of args gives the argument names.
quote | a logical value indicating whether to quote the arguments.
envir | an environment within which to evaluate the call. This will be most useful if what is a character string and the arguments are symbols or quoted expressions.

Details

If quote is FALSE, the default, then the arguments are evaluated (in the calling environment, not envir.). If quote is TRUE then each argument is quoted (see quote) so that the effect of argument evaluation is to remove the quote – leaving the original argument unevaluated when the call is constructed.

The behavior of some functions, such as substitute, will not be the same for functions evaluated using do.call as if they were evaluated from the interpreter. The precise semantics are currently undefined and subject to change.

Value

The result of the (evaluated) function call.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

call which creates an unevaluated call.

Examples

do.call("complex", list(imag = 1:3))

## if we already have a list (e.g. a data frame)
## we need c() to add further arguments
tmp <- expand.grid(letters[1:2], 1:3, c("+", "-"))
do.call("paste", c(tmp, sep=""))

do.call(paste, list(as.name("A"), as.name("B")), quote=TRUE)

## examples of where objects will be found.
A <- 2
f <- function(x) print(x^2)
env <- new.env()
assign("A", 10, envir = env)
assign("f", f, envir = env)
f <- function(x) print(x)
f(A)                                    # 2
do.call("f", list(A))                   # 2
do.call("f", list(A), envir=env)        # 4
do.call(f, list(A), envir=env)          # 2
do.call("f", list(quote(A)), envir=env) # 100
do.call(f, list(quote(A)), envir=env)   # 10
do.call("f", list(as.name("A")), envir=env) # 100

eval(call("f", A))                      # 2
eval(call("f", quote(A)))               # 2
eval(call("f", A), envir=env)           # 4
eval(call("f", quote(A)), envir=env)    # 100


Double Precision Vectors

Description

Create, coerce to or test for a double-precision vector.

Usage

double(length = 0)
as.double(x, ...)
is.double(x)

single(length = 0)
as.single(x, ...)

Arguments

length | desired length.
x | object to be coerced or tested.
... | further arguments passed to or from other methods.

Value

double creates a double precision vector of the specified length. The elements of the vector are all equal to 0.
as.double attempts to coerce its argument to be of double type: like as.vector it strips attributes including names. Character strings containing either a decimal representation or a heaxadecimal representation (starting with 0x or 0X) can be converted.
is.double returns TRUE or FALSE depending on whether its argument is of double type or not. It is generic: you can write methods to handle specific classes of objects, see InternalMethods.

Note

R has no single precision data type. All real numbers are stored in double precision format. The functions as.single and single are identical to as.double and double except they set the attribute Csingle that is used in the .C and .Fortran interface, and they are intended only to be used in that context.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

integer, numeric.

Examples

is.double(1)
all(double(3) == 0)


Write an Internal Object to a File

Description

Writes an ASCII text representation of an R object to a file or connection, or uses one to recreate the object.

Usage

dput(x, file = "", control = "showAttributes")
dget(file)

Arguments

x | an object.
file | either a character string naming a file or a connection. "" indicates output to the console.
control | character vector indicating deparsing options. See .deparseOpts for their description.

Details

dput opens file and deparses the object x into that file. The object name is not written (contrary to dump). If x is a function the associated environment is stripped. Hence scoping information can be lost.

Deparsing an object is difficult, and not always possible. With the default control = c("showAttributes"), dput() attempts to deparse in a way that is readable, but for more complex or unusual objects, not likely to be parsed as identical to the original. Use control = "all" for the most complete deparsing; use control = NULL for the simplest deparsing, not even including attributes.

dput will warn if fewer characters were written to a file than expected, which may indicate a full or corrupt file system.

To display saved source rather than deparsing the internal representation include "useSource" in control. R currently saves source only for function definitions.

Note

To avoid the risk of a source attribute out of sync with the actual function definition, the source attribute of a function will never be written as an attribute.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

deparse, dump, write.

Examples

## Write an ASCII version of mean to the file "foo"
dput(mean, "foo")
## And read it back into 'bar'
bar <- dget("foo")
unlink("foo")
## Create a function with comments
baz <- function(x) {
  # Subtract from one
  1-x
}
## and display it
dput(baz)
## and now display the saved source
dput(baz, control = "useSource")


Drop Redundant Extent Information

Description

Delete the dimensions of an array which have only one level.

Usage

drop(x)

Arguments

x an array (including a matrix).

Value

If x is an object with a dim attribute (e.g., a matrix or array), then drop returns an object like x, but with any extents of length one removed. Any accompanying dimnames attribute is adjusted and returned with x.
Array subsetting ([) performs this reduction unless used with drop = FALSE, but sometimes it is useful to invoke drop directly.

See Also

drop1 which is used for dropping terms in models.

Examples

dim(drop(array(1:12, dim=c(1,3,1,1,2,1,2))))# = 3 2 2
drop(1:3 %*% 2:4)# scalar product


Text Representations of R Objects

Description

This function takes a vector of names of R objects and produces text representations of the objects on a file or connection. A dump file can usually be sourced into another R (or S) session.

Usage

dump(list, file = "dumpdata.R", append = FALSE,
     control = "all", envir = parent.frame(), evaluate = TRUE)

Arguments

list | character. The names of one or more R objects to be dumped.
file | either a character string naming a file or a connection. "" indicates output to the console.
append | if TRUE, output will be appended to file; otherwise, it will overwrite the contents of file.
control | character vector indicating deparsing options. See .deparseOpts for their description.
envir | the environment to search for objects.
evaluate | logical. Should promises be evaluated?

Details

If some of the objects named do not exist (in scope), they are omitted, with a warning. If file is a file and no objects exist then no file is created.

At present sourceing may not produce an identical copy of dumped objects. A warning is issued if it is likely that problems will arise, for example when dumping exotic objects such as environments and external pointers.

dump will also warn if fewer characters were written to a file than expected, which may indicate a full or corrupt file system.

A dump file can be sourced into another R (or perhaps S) session, but the function save is designed to be used for transporting R data, and will work with R objects that dump does not handle.

To produce a more readable representation of an object, use control = NULL. This will skip attributes, and will make other simplifications that make source less likely to produce an identical copy. See deparse for details.

To deparse the internal function representation rather than displaying the saved source, use control = c("keepInteger", "quoteExpressions", "showAttributes", "warnIncomplete"). This will lose all formatting and comments, but may be useful in those cases where the saved source is no longer correct.

Promises will normally only be encountered by users as a result of lazy-loading (when the default evaluate = TRUE is essential) and after the use of delayedAssign, when evaluate = FALSE might be intended.

Value

An invisible character vector containing the names of the objects which were dumped.

Note

As dump is defined in the base namespace, the base package will be searched before the global environment unless dump is called from the top level or the envir argument is given explicitly.

To avoid the risk of a source attribute out of sync with the actual function definition, the source attribute of a function will never be dumped as an attribute.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

dput, dget, write.
save for a more reliable way to save R objects.

Examples

x <- 1; y <- 1:10
dump(ls(patt='^[xyz]'), "xyz.Rdmped")
print(.Last.value)
unlink("xyz.Rdmped")


Determine Duplicate Elements

Description

Determines which elements of a vector or data frame are duplicates of elements with smaller subscripts, and returns a logical vector indicating which elements (rows) are duplicates.

Usage

duplicated(x, incomparables = FALSE, ...)

## S3 method for class 'array':
duplicated(x, incomparables = FALSE, MARGIN = 1, ...)

Arguments

x | a vector or a data frame or an array or NULL.
incomparables | a vector of values that cannot be compared. Currently, FALSE is the only possible value, meaning that all values can be compared.
... | arguments for particular methods.
MARGIN | the array margin to be held fixed: see apply.

Details

This is a generic function with methods for vectors (including lists), data frames and arrays (including matrices).

The data frame method works by pasting together a character representation of the rows separated by \r, so may be imperfect if the data frame has characters with embedded carriage returns or columns which do not reliably map to characters.

The array method calculates for each element of the sub-array specified by MARGIN if the remaining dimensions are identical to those for an earlier element (in row-major order). This would most commonly be used to find duplicated rows (the default) or columns (with MARGIN = 2).

Warning

Using this for lists is potentially slow, especially if the elements are not atomic vectors (see vector) or differ only in their attributes. In the worst case it is O(n^2).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

unique.

Examples

x <- c(9:20, 1:5, 3:7, 0:8)
## extract unique elements
(xu <- x[!duplicated(x)])
## xu == unique(x) but unique(x) is more efficient

duplicated(iris)[140:143]

duplicated(iris3, MARGIN = c(1, 3))


Foreign Function Interface

Description

Load or unload shared libraries, and test whether a C function or Fortran subroutine is available.

Usage

dyn.load(x, local = TRUE, now = TRUE)
dyn.unload(x)

is.loaded(symbol, PACKAGE = "", type = "")

Arguments

x | a character string giving the pathname to a shared library or DLL.
local | a logical value controlling whether the symbols in the shared library are stored in their own local table and not shared across shared libraries, or added to the global symbol table. Whether this has any effect is system-dependent. It is ignored on Windows.
now | a logical controlling whether all symbols are resolved (and relocated) immediately the library is loaded or deferred until they are used. This control is useful for developers testing whether a library is complete and has all the necessary symbols, and for users to ignore missing symbols. Whether this has any effect is system-dependent. It is ignored on Windows.
symbol | a character string giving a symbol name.
PACKAGE | if supplied, confine the search for the name to the DLL given by this argument (plus the conventional extension, .so, .sl, .dll, ...). This is intended to add safety for packages, which can ensure by using this argument that no other package can override their external symbols. Use PACKAGE="base" for symbols linked in to R. This is used in the same way as in .C, .Call, .Fortran and .External functions
type | The type of symbol to look for: can be any ("", the default), "Fortran", "Call" or "External".

Details

See ‘See Also’ and the Writing R Extensions and R Installation and Administration manuals for how to create and install a suitable shared library. Note that unlike some versions of S-PLUS, dyn.load does not load an object (‘.o’) file but a shared library or DLL.

Unfortunately a very few platforms (Compaq Tru64) do not handle the PACKAGE argument correctly, and may incorrectly find symbols linked into R.

The additional arguments to dyn.load mirror the different aspects of the mode argument to the dlopen() routine on UNIX systems. They are available so that users can exercise greater control over the loading process for an individual library. In general, the defaults values are appropriate and you should override them only if there is good reason and you understand the implications.

External code must not change the floating point control word, but many DLLs do so. Common changes are to set it to use 53 bit precision instead of R's default 64 bit precision, or to unmask some exceptions. dyn.load detects such changes, and restores R's control word to its default value of hex 8001F. This may cause the DLL to malfunction; if so, it should be rewritten to save and restore the control word itself. If warn.FPU is set to TRUE using the options function, a warning will be printed. (If the warning says that the control word was changed from some other value than 8001F, please report the circumstances to the Windows maintainers: that probably indicates an internal bug.)

Value

The function dyn.load is used for its side effect which links the specified shared library to the executing R image. Calls to .C, .Call, .Fortran and .External can then be used to execute compiled C functions or Fortran subroutines contained in the library. The return value of dyn.load is an object of class DLLInfo. See getLoadedDLLs for information about this class.
The function dyn.unload unlinks the shared library.
is.loaded checks if the symbol name is loaded and hence available for use in .C or .Fortran or .Call or .Exernal: it requires the name you would give to .C etc and not (as in S) that remapped by deprecated functions symbol.C or symbol.For. It will succeed if any one of the four calling functions would succeed in using the entry point unless type is specified: for Fortran entry points is.loaded(symbol.For("symbol")) will also succeed unless the registration mechanism has been used.

Warning

Do not use dyn.unload on a shared object loaded by library.dynam: use library.dynam.unload.

Note

The creation of shared libraries and the runtime linking of them into executing programs is very platform dependent. In recent years there has been some simplification in the process because the C subroutine call dlopen has become the standard for doing this under UNIX. Under UNIX dyn.load uses the dlopen mechanism and should work on all platforms which support it. On Windows it uses the standard mechanisms for loading 32-bit DLLs.

The original code for loading DLLs in UNIX was provided by Heiner Schwarte. The compatibility code for HP-UX was provided by Luke Tierney.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

library.dynam to be used inside a package's .First.lib initialization.

SHLIB for how to create suitable DLLs.

.C, .Fortran, .External, .Call.

Examples

is.loaded("hcass2") #-> probably TRUE, as stats is loaded
is.loaded("supsmu") # Fortran entry point in stats
is.loaded("supsmu", "stats", "Fortran")
is.loaded("PDF", type = "External")


Apply a Function over values in an environment

Description

eapply applies FUN to the named values from an environment and returns the results as a list. The user can request that all named objects are used (normally names that begin with a dot are not). The output is not sorted and no parent environments are searched.

Usage

eapply(env, FUN, ..., all.names = FALSE)

Arguments

env | environment to be used.
FUN | the function to be applied, found via match.fun. In the case of functions like +, %*%, etc., the function name must be backquoted or quoted.
... | optional arguments to FUN.
all.names | a logical indicating whether to apply the function to all values

See Also

lapply.

Examples

env <- new.env()
env$a <- 1:10
env$beta <- exp(-3:3)
env$logic <- c(TRUE,FALSE,FALSE,TRUE)
# compute the list mean for each list element
eapply(env,mean)
# median and quartiles for each list element
eapply(env, quantile, probs = 1:3/4)
eapply(env, quantile)


Spectral Decomposition of a Matrix

Description

Computes eigenvalues and eigenvectors of real or complex matrices.

Usage

eigen(x, symmetric, only.values = FALSE, EISPACK = FALSE)

Arguments

x | a matrix whose spectral decomposition is to be computed.
symmetric | if TRUE, the matrix is assumed to be symmetric (or Hermitian if complex) and only its lower triangle is used. If symmetric is not specified, the matrix is inspected for symmetry.
only.values | if TRUE, only the eigenvalues are computed and returned, otherwise both eigenvalues and eigenvectors are returned.
EISPACK | logical. Should EISPACK be used (for compatibility with R < 1.7.0)?

Details

By default eigen uses the LAPACK routines DSYEVR, DGEEV, ZHEEV and ZGEEV whereas eigen(EISPACK=TRUE) provides an interface to the EISPACK routines RS, RG, CH and CG.

If symmetric is unspecified, the code attempts to determine if the matrix is symmetric up to plausible numerical inaccuracies. It is faster and surer to set the value yourself.

eigen is preferred to eigen(EISPACK = TRUE) for new projects, but its eigenvectors may differ in sign and (in the asymmetric case) in normalization. (They may also differ between methods and between platforms.)

Computing the eigenvectors is the slow part for large matrices.

Computing the eigendecomposition of a matrix is subject to errors on a real-world computer: the definitive analysis is Wilkinson (1965). All you can hope for is a solution to a problem suitably close to x. So even though a real asymmetric x may have an algebraic solution with repeated real eigenvalues, the computed solution may be of a similar matrix with complex conjugate pairs of eigenvalues.

Value

The spectral decomposition of x is returned as components of a list with components

values | a vector containing the p eigenvalues of x, sorted in decreasing order, according to Mod(values) in the asymmetric case when they might be complex (even for real matrices). For real asymmetric matrices the vector will be complex only if complex conjugate pairs of eigenvalues are detected.
vectors | either a p * p matrix whose columns contain the eigenvectors of x, or NULL if only.values is TRUE. For eigen(, symmetric = FALSE, EISPACK =TRUE) the choice of length of the eigenvectors is not defined by EISPACK. In all other cases the vectors are normalized to unit length. Recall that the eigenvectors are only defined up to a constant: even when the length is specified they are still only defined up to a scalar of modulus one (the sign for real matrices).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Smith, B. T, Boyle, J. M., Dongarra, J. J., Garbow, B. S., Ikebe,Y., Klema, V., and Moler, C. B. (1976). Matrix Eigensystems Routines – EISPACK Guide. Springer-Verlag Lecture Notes in Computer Science.

Anderson. E. and ten others (1999) LAPACK Users' Guide. Third Edition. SIAM.
Available on-line at http://www.netlib.org/lapack/lug/lapack_lug.html.

Wilkinson, J. H. (1965) The Algebraic Eigenvalue Problem. Clarendon Press, Oxford.

See Also

svd, a generalization of eigen; qr, and chol for related decompositions.

To compute the determinant of a matrix, the qr decomposition is much more efficient: det.

capabilities to test for IEEE 754 arithmetic.

Examples

eigen(cbind(c(1,-1),c(-1,1)))
eigen(cbind(c(1,-1),c(-1,1)), symmetric = FALSE)# same (different algorithm).

eigen(cbind(1,c(1,-1)), only.values = TRUE)
eigen(cbind(-1,2:1)) # complex values
eigen(print(cbind(c(0,1i), c(-1i,0))))# Hermite ==> real Eigen values
## 3 x 3:
eigen(cbind( 1,3:1,1:3))
eigen(cbind(-1,c(1:2,0),0:2)) # complex values


Encode Character Vector as for Printing

Description

encodeString escapes the strings in a character vector in the same way print.default does, and optionally fits the encoded strings within a field width.

Usage

encodeString(x, width = 0, quote = "", na.encode = TRUE,
             justify = c("left", "right", "centre", "none"))

Arguments

x | A character vector, or an object that can be coerced to one by as.character.
width | integer: the minimum field width. If NULL or NA, this is taken to be the largest field width needed for any element of x.
quote | character: quoting character, if any.
na.encode | logical: should NA strings be encoded?
justify | character: partial matches are allowed. If padding to the minimum field width is needed, how should spaces be inserted? justify == "none" is equivalent to width = 0, for consistency with format.default.

Details

This escapes backslash and the control characters \a (bell), \b (backspace), \f (formfeed), \n (line feed), \r (carriage return), \t (tab), \v (vertical tab) and \0 (nul) as well as any non-printable characters in a single-byte locale, which are printed in octal notation (\xyz with leading zeroes). (Windows' reporting of printable characters is unreliable, so all other control characters are regarded as non-printable, and all characters with codes 32–255 as printable in a single-byte locale.) See print.default for how non-printable characters are handled in multi-byte locales.

If quote is a single or double quote any embedded quote of the same type is escaped. Note that justification is of the quoted string, hence spaces are added outside the quotes.

Value

A character vector of the same length as x, with the same attributes (including names and dimensions) but with no class set.

Note

The default for width is different from format.default, which does similar things for character vectors but without encoding using escapes.

See Also

print.default

Examples

x <- "ab\bc\ndef"
print(x)
cat(x) # interprets escapes
cat(encodeString(x), "\n", sep="") # similar to print()

factor(x) # makes use of this to print the levels

x <- c("a", "ab", "abcde")
encodeString(x, w = NA) # left justification
encodeString(x, w = NA, justify = "c")
encodeString(x, w = NA, justify = "r")
encodeString(x, w = NA, quote = "'", justify = "r")


Environment Access

Description

Get, set, test for and create environments.

Usage

environment(fun = NULL)
environment(fun) <- value

is.environment(obj)

.GlobalEnv
globalenv()
.BaseNamespaceEnv

emptyenv()
baseenv()

new.env(hash = FALSE, parent = parent.frame())

parent.env(env)
parent.env(env) <- value

Arguments

fun | a function, a formula, or NULL, which is the default.
value | an environment to associate with the function
obj | an arbitrary R object.
hash | a logical, if TRUE the environment will be hashed
parent | an environment to be used as the enclosure of the environment created.
env | an environment

Details

Environments consist of a frame, or collection of named objects, and a pointer to an enclosing environment. The most common example is the frame of variables local to a function call; its enclosure is the environment where the function was defined. The enclosing environment is distinguished from the parent frame: the latter (returned by parent.frame) refers to the environment of the caller of a function.

When get or exists search an environment with the default inherits = TRUE, they look for the variable in the frame, then in the enclosing frame, and so on.

The global environment .GlobalEnv, more often known as the user's workspace, is the first item on the search path. It can also be accessed by globalenv(). On the search path, each item's enclosure is the next item.

The object .BaseNamespaceEnv is the namespace environment for the base package. The environment of the base package itself is available as baseenv(). The ultimate enclosure of any environment is the empty environment emptyenv(), to which nothing may be assigned. If one follows the parent.env() chain of enclosures back far enough from any environment, eventually one reaches the empty environment.

The replacement function parent.env<- is extremely dangerous as it can be used to destructively change environments in ways that violate assumptions made by the internal C code. It may be removed in the near future.

is.environment is generic: you can write methods to handle specific classes of objects, see InternalMethods.

Value

If fun is a function or a formula then environment(fun) returns the environment associated with that function or formula. If fun is NULL then the current evaluation environment is returned.
The replacement form sets the environment of the function or formula fun to the value given.
is.environment(obj) returns TRUE iff obj is an environment.
new.env returns a new (empty) environment enclosed in the parent's environment, by default.
parent.env returns the parent environment of its argument.
parent.env<- sets the enclosing environment of its first argument.

See Also

The envir argument of eval, get, and exists.

ls may be used to view the objects in an environment.

Examples

f <- function() "top level function"

##-- all three give the same:
environment()
environment(f)
.GlobalEnv

ls(envir=environment(approxfun(1:2,1:2, method="const")))

is.environment(.GlobalEnv) # TRUE

e1 <- new.env(parent = baseenv())  # this one has enclosure package:base.
e2 <- new.env(parent = e1)
assign("a", 3, env=e1)
ls(e1)
ls(e2)
exists("a", env=e2)     # this succeeds by inheritance
exists("a", env=e2, inherits = FALSE)
exists("+", env=e2)     # this succeeds by inheritance


Evaluate an (Unevaluated) Expression

Description

Evaluate an R expression in a specified environment.

Usage

eval(expr, envir = parent.frame(),
           enclos = if(is.list(envir) || is.pairlist(envir))
                       parent.frame() else baseenv())
evalq(expr, envir, enclos)
eval.parent(expr, n = 1)
local(expr, envir = new.env())

Arguments

expr | an object to be evaluated. See Details.
envir | the environment in which expr is to be evaluated. May also be NULL, a list, a data frame, a pairlist or an integer as specified to sys.call.
enclos | Relevant when envir is a (pair)list or a data frame. Specifies the enclosure, i.e., where R looks for objects not found in envir. This can be NULL (interpreted as the base package environment) or an environment.
n | number of parent generations to go back

Details

eval evaluates the expr argument in the environment specified by envir and returns the computed value. If envir is not specified, then the default is parent.frame() (the environment where the call to eval was made).

Objects to be evaluated can be of types call or expression or symbol (when the symbol is looked up in the current scope and its binding is evaluated), a promise or any of the basic types such as vectors, functions and environments (which are returned unchanged).

The evalq form is equivalent to eval(quote(expr), ...). eval evaluates its first argument in the current scope before passing it to the evaluator: evalq avoids this.

eval.parent(expr, n) is a shorthand for eval(expr, parent.frame(n)).

If envir is a list (such as a data frame) or pairlist, it is copied into a temporary environment (with enclosure enclos), and the temporary environment is used for evaluation. So if expr changes any of the components named in the (pair)list, the changes are lost.

If envir is NULL it is interpreted as an empty list so no values could be found in envir and look-up goes directly to enclos.

local evaluates an expression in a local environment. It is equivalent to evalq except that its default argument creates a new, empty environment. This is useful to create anonymous recursive functions and as a kind of limited namespace feature since variables defined in the environment are not visible from the outside.

Note

Due to the difference in scoping rules, there are some differences between R and S in this area. In particular, the default enclosure in S is the global environment.

When evaluating expressions in data frames that has been passed as argument to a function, the relevant enclosure is often the caller's environment, i.e., one needs eval(x, data, parent.frame()).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole. (eval only.)

See Also

expression, quote, sys.frame, parent.frame, environment.

Further, force to force evaluation, typically of function arguments.

Examples

eval(2 ^ 2 ^ 3)
mEx <- expression(2^2^3); mEx; 1 + eval(mEx)
eval({ xx <- pi; xx^2}) ; xx

a <- 3 ; aa <- 4 ; evalq(evalq(a+b+aa, list(a=1)), list(b=5)) # == 10
a <- 3 ; aa <- 4 ; evalq(evalq(a+b+aa, -1), list(b=5))        # == 12

ev <- function() {
   e1 <- parent.frame()
   ## Evaluate a in e1
   aa <- eval(expression(a),e1)
   ## evaluate the expression bound to a in e1
   a <- expression(x+y)
   list(aa = aa, eval = eval(a, e1))
}
tst.ev <- function(a = 7) { x <- pi; y <- 1; ev() }
tst.ev()#-> aa : 7,  eval : 4.14

a <- list(a=3, b=4)
with(a, a <- 5) # alters the copy of a from the list, discarded.

##
## Example of evalq()
##

N <- 3
env <- new.env()
assign("N", 27, envir=env)
## this version changes the visible copy of N only, since the argument
## passed to eval is '4'.
eval(N <- 4, env)
N
get("N", envir=env)
## this version does the assignment in env, and changes N only there.
evalq(N <- 5, env)
N
get("N", envir=env)

##
## Uses of local()
##

# Mutual recursives.
# gg gets value of last assignment, an anonymous version of f.

gg <- local({
    k <- function(y)f(y)
    f <- function(x) if(x) x*k(x-1) else 1
})
gg(10)
sapply(1:5, gg)

# Nesting locals. a is private storage accessible to k
gg <- local({
    k <- local({
        a <- 1
        function(y){print(a <<- a+1);f(y)}
    })
    f <- function(x) if(x) x*k(x-1) else 1
})
sapply(1:5, gg)

ls(envir=environment(gg))
ls(envir=environment(get("k", envir=environment(gg))))


Is an Object Defined?

Description

Look for an R object of the given name.

Usage

exists(x, where = -1, envir = , frame, mode = "any",
       inherits = TRUE)

Arguments

x | a variable name (given as a character string).
where | where to look for the object (see the details section); if omitted, the function will search as if the name of the object appeared unquoted in an expression.
envir | an alternative way to specify an environment to look in, but it is usually simpler to just use the where argument.
frame | a frame in the calling list. Equivalent to giving where as sys.frame(frame).
mode | the mode or type of object sought: see the Details section.
inherits | should the enclosing frames of the environment be searched?

Details

The where argument can specify the environment in which to look for the object in any of several ways: as an integer (the position in the search list); as the character string name of an element in the search list; or as an environment (including using sys.frame to access the currently active function calls). The envir argument is an alternative way to specify an environment, but is primarily there for back compatibility.

This function looks to see if the name x has a value bound to it in the specified environment. If inherits is TRUE and a value is not found for x in the specified environment, the enclosing frames of the environment are searched until the name x is encountered. See environment and the ‘R Language Definition’ manual for details about the structure of environments and their enclosures.

Warning: inherits = TRUE is the default behaviour for R but not for S.

If mode is specified then only objects of that type are sought. The mode may specify one of the collections "numeric" and "function" (see mode): any member of the collection will suffice. (This is true even if a member of a collection is specified, so for example mode="special" will seek any type of function.)

Value

Logical, true if and only if an object of the correct name and mode is found.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

get.

Examples

##  Define a substitute function if necessary:
if(!exists("some.fun", mode="function"))
  some.fun <- function(x) { cat("some.fun(x)\n"); x }
search()
exists("ls", 2) # true even though ls is in pos=3
exists("ls", 2, inherits = FALSE) # false


Create a Data Frame from All Combinations of Factors

Description

Create a data frame from all combinations of the supplied vectors or factors. See the description of the return value for precise details of the way this is done.

Usage

expand.grid(..., KEEP.OUT.ATTRS = TRUE)

Arguments

... | vectors, factors or a list containing these.
KEEP.OUT.ATTRS | a logical indicating the "out.attrs" attribute (see below) should be computed and returned.

Value

A data frame containing one row for each combination of the supplied factors. The first factors vary fastest. The columns are labelled by the factors if these are supplied as named arguments or named components of a list.
Attribute "out.attrs" is a list which gives the dimension and dimnames for use by predict methods.

References

Chambers, J. M. and Hastie, T. J. (1992) Statistical Models in S. Wadsworth & Brooks/Cole.

See Also

combn (package utils) for the generation of all combinations of n elements, taken m at a time.

Examples

expand.grid(height = seq(60, 80, 5), weight = seq(100, 300, 50),
            sex = c("Male","Female"))

x <- seq(0,10, length=100)
y <- seq(-1,1, length=20)
d1 <- expand.grid(x=x, y=y)
d2 <- expand.grid(x=x, y=y, KEEP.OUT.ATTRS = FALSE)
object.size(d1) - object.size(d2)
##-> 5992 or 8832 (on 32- / 64-bit platform)


Unevaluated Expressions

Description

Creates or tests for objects of mode "expression".

Usage

expression(...)

is.expression(x)
as.expression(x, ...)

Arguments

... | valid R calls, symbols or constants.
x | an arbitrary R object.

Details

‘Expression’ here is not being used in its colloquial sense, that of mathematical expressions. Those are calls (see call) in R, and an R expression vector is a list of calls etc, typically as returned by parse.

As an object of mode "expression" is a list, it can be subsetted by both [ and by [[, the latter extracting individual calls.

Value

expression returns a vector of type "expression" containing its arguments (unevaluated).
is.expression returns TRUE if expr is an expression object and FALSE otherwise.
as.expression attempts to coerce its argument into an expression object.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

call, eval, function. Further, text and legend for plotting mathematical expressions.

Examples

length(ex1 <- expression(1+ 0:9))# 1
ex1
eval(ex1)# 1:10

length(ex3 <- expression(u,v, 1+ 0:9))# 3
mode(ex3 [3]) # expression
mode(ex3[[3]])# call
rm(ex3)


Extract or Replace Parts of an Object

Description

Operators acting on vectors, matrices, arrays and lists to extract or replace parts.

Usage

x[i]
x[i, j, ... , drop = TRUE]
x[[i]]
x[[i, j, ...]]
x$name

Arguments

x | object from which to extract element(s) or in which to replace element(s).
i, j, ..., name | indices specifying elements to extract or replace. i, j are numeric or character vectors or empty (missing) or NULL whereas name must be a character string or an (unquoted or backtick quoted) name. Numeric values are coerced to integer as by as.integer. For extraction with [[ and $ character strings are normally (see under Environments) partially matched to the names of the object if exact matching does not succeed. For [-indexing only: i, j, ... can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. i, j, ... can also be negative integers, indicating elements/slices to leave out of the selection. When indexing arrays by [ a single argument i can be a matrix with as many columns as there are dimensions of x; the result is then a vector with elements corresponding to the sets of indices in each row of i. An index value of NULL is treated as if it were integer(0).
drop | For matrices and arrays. If TRUE the result is coerced to the lowest possible dimension (see the examples). This only works for extracting elements, not for the replacement.

Details

These operators are generic. You can write methods to handle indexing of specific classes of objects, see InternalMethods as well as [.data.frame and [.factor. The descriptions here apply only to the default methods. Note that separate methods are required for the replacement functions [<-, [[<- and $<- for use when indexing occurs on the assignment side of an expression.

The most important distinction between [, [[ and $ is that the [ can select more than one element whereas the other two select a single element.

The default methods work somewhat differently for atomic vectors, matrices/arrays and for recursive (list-like, see is.recursive) objects. $ returns NULL except for recursive objects, and is only discussed in the section below on recursive objects.

Subsetting (except by an empty index) will drop all attributes except names, dim and dimnames.

Indexing can occur on the right-hand-side of an expression for extraction, or on the left-hand-side for replacement. When an index expression appears on the left side of an assignment (known as subassignment) then that part of x is set to the value of the right hand side of the assignment. In this case no partial matching of indices is done, and the left-hand-side is coerced as needed to accept the values. Attributes are preserved (although names, dim and dimnames will be adjusted suitably).

Atomic vectors

The usual form of indexing is "[". "[[" can be used to select a single element, but "[" can also do so (but will not partially match a character index).

The index object i can be numeric, logical, character or empty. Indexing by factors is allowed and is equivalent to indexing by the numeric codes (see factor) and not by the character values which are printed (for which use [as.character(i)]).

An empty index selects all values: this is most often used to replace all the entries but keep the attributes.

Matrices and arrays

Matrices and arrays are vectors with a dimension attribute and so all the vector forms of indexing can be used with a single index. The result will be an unnamed vector unless x is one-dimensional when it will be a one-dimensional array.

The most common form of indexing a k-dimensional array is to specify k indices to [. As for vector indexing, the indices can be numeric, logical, character, empty or even factor. An empty index (a comma separated blank) indicates that all entries in that dimension are selected. The argument drop applies to this form of indexing.

A third form of indexing is via a numeric matrix with the one column for each dimension: each row of the index matrix then selects a single element of the array, and the result is a vector. Negative indices are not allowed in the index matrix. NA and zero values are allowed: rows of an index matrix containing a zero are ignored, whereas rows containing an NA produce an NA in the result.

A vector obtained by matrix indexing will be unnamed unless x is one-dimensional when the row names (if any) will be indexed to provide names for the result.

Recursive (list-like) objects

Indexing by [ is similar to atomic vectors and selects a list of the specified element(s).

Both [[ and $ select a single element of the list. The main difference is that $ does not allow computed indices, whereas [[ does. x$name is equivalent to x[["name"]].

[ and [[ are sometimes applied to other recursive objects such as calls and expressions. Pairlists are coerced to lists for extraction by [, but all three operators can be used for replacement.

[[ can be applied recursively to lists, so that if the single index i is a vector of length p, alist[[i]] is equivalent to alist[[i1]]...[[ip]] providing all but the final indexing results in a list.

When $<- is applied to a NULL x, it first coerces x to list(). This is what also happens with [[<- if the replacement value value is of length greater than one: if value has length 1 or 0, x is first coerced to a zero-length vector of the type of value.

Environments

Both $ and [[ can be applied to environments. Only character arguments are allowed and no partial matching is done. The semantics of these operations are those of get(i, env=x, inherits=FALSE). If no match is found then NULL is returned. The assignment versions, $<- and [[<-, can also be used. Again, only character arguments are allowed. The semantics in this case are those of assign(i, value, env=x, inherits=FALSE). Such an assignment will either create a new binding or change the existing binding in x.

NAs in indexing

When extracting, a numerical, logical or character NA index picks an unknown element and so returns NA in the corresponding element of a logical, integer, numeric, complex or character result, and NULL for a list. (It returns 00 for a raw result.]

When replacing (that is using indexing on the lhs of an assignment) NA does not select any element to be replaced. As there is ambiguity as to whether an element of the rhs should be used or not, this is only allowed if the rhs value is of length one (so the two interpretations would have the same outcome).

Argument matching

Note that these operations do not match their index arguments in the standard way: argument names are ignored and positional matching only is used. So m[j=2,i=1] is equivalent to m[2,1] and not to m[1,2].

This may not be true for methods defined for them; for example it is not true for the data.frame methods described in [.data.frame.

To avoid confusion, do not name index arguments (but drop must be named).

Note

S uses partial matching when extracting by [ (Becker et al p. 358) whereas R does not.

The documented behaviour of S is that an NA replacement index ‘goes nowhere’ but uses up an element of value (Becker et al p. 359). However, that is not the current behaviour of S-PLUS.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

list, array, matrix.

[.data.frame and [.factor for the behaviour when applied to data.frame and factors.

Syntax for operator precedence, and the R Language reference manual about indexing details.

Examples

x <- 1:12; m <- matrix(1:6,nr=2); li <- list(pi=pi, e = exp(1))
x[10]                 # the tenth element of x
x <- x[-1]            # delete the 1st element of x
m[1,]                 # the first row of matrix m
m[1, , drop = FALSE]  # is a 1-row matrix
m[,c(TRUE,FALSE,TRUE)]# logical indexing
m[cbind(c(1,2,1),3:1)]# matrix index
m <- m[,-1]           # delete the first column of m
li[[1]]               # the first element of list li
y <- list(1,2,a=4,5)
y[c(3,4)]             # a list containing elements 3 and 4 of y
y$a                   # the element of y named a

## non-integer indices are truncated:
(i <- 3.999999999) # "4" is printed
(1:5)[i]  # 3

## recursive indexing into lists
z <- list( a=list( b=9, c='hello'), d=1:5)
unlist(z)
z[[c(1, 2)]]
z[[c(1, 2, 1)]]  # both "hello"
z[[c("a", "b")]] <- "new"
unlist(z)

## check $ and [[ for environments
e1 <- new.env()
e1$a <- 10
e1[["a"]]
e1[["b"]] <- 20
e1$b
ls(e1)


Extract or Replace Parts of a Data Frame

Description

Extract or replace subsets of data frames.

Usage

x[i]
x[i] <- value
x[i, j, drop]
x[i, j] <- value

x[[i]]
x[[i]] <- value
x[[i, j]]
x[[i, j]] <- value

x$name
x$name <- value

Arguments

x | data frame.
i, j | elements to extract or replace. i, j are numeric or character or, for [ only, empty. Numeric values are coerced to integer as if by as.integer. For replacement by [, a logical matrix is allowed.
drop | logical. If TRUE the result is coerced to the lowest possible dimension. The default is to drop if only one column is left, but not to drop if only one row is left.
value | A suitable replacement value: it will be repeated a whole number of times if necessary and it may be coerced: see the Coercion section. If NULL, deletes the column if a single column is selected.
name | name or literal character string.

Details

Data frames can be indexed in several modes. When [ and [[ are used with a single index, they index the data frame as if it were a list. In this usage a drop argument is ignored, with a warning. Using $ is equivalent to using [[ with a single index.

When [ and [[ are used with two indices they act like indexing a matrix: [[ can only be used to select one element.

If [ returns a data frame it will have unique (and non-missing) row names, if necessary transforming the row names using make.unique. Similarly, column names will be transformed (if columns are selected more than once).

When drop =TRUE, this is applied to the subsetting of any matrices contained in the data frame as well as to the data frame itself.

The replacement methods can be used to add whole column(s) by specifying non-existent column(s), in which case the column(s) are added at the right-hand edge of the data frame and numerical indices must be contiguous to existing indices. On the other hand, rows can be added at any row after the current last row, and the columns will be in-filled with missing values. Missing values in the indices are not allowed for replacement.

For [ the replacement value can be a list: each element of the list is used to replace (part of) one column, recycling the list as necessary. If columns specified by number are created, the names (if any) of the corresponding list elements are used to name the columns. If the replacement is not selecting rows, list values can contain NULL elements which will cause the corresponding columns to be deleted. (See the Examples.)

Matrixing indexing using [ is not recommended, and barely supported. For extraction, x is first coerced to a matrix. For replacement a logical matrix (only) can be used to select the elements to be replaced in the same way as for a matrix.

Value

For [ a data frame, list or a single column (the latter two only when dimensions have been dropped). If matrix indexing is used for extraction a matrix results.
For [[ a column of the data frame (extraction with one index) or a length-one vector (extraction with two indices).
For [<-, [[<- and $<-, a data frame.

Coercion

The story over when replacement values are coerced is a complicated one, and one that has changed during R's development. This section is a guide only.

When [ and [[ are used to add or replace a whole column, no coercion takes place but value will be replicated (by calling the generic function rep) to the right length if an exact number of repeats can be used.

When [ is used with a logical matrix, each value is coerced to the type of the column in which it is to be placed.

When [ and [[ are used with two indices, the column will be coerced as necessary to accommodate the value.

Note that when the replacement value is an array (including a matrix) it is not treated as a series of columns (as data.frame and as.data.frame do) but inserted as a single column.

Warning

The default behaviour when only one row is left is equivalent to specifying drop = FALSE. To drop from a data frame to a list, drop = TRUE has to be specified explicitly.

See Also

subset which is often easier for extraction, data.frame, Extract.

Examples

sw <- swiss[1:5, 1:4]  # select a manageable subset

sw[1:3]      # select columns
sw[, 1:3]    # same
sw[4:5, 1:3] # select rows and columns
sw[1]        # a one-column data frame
sw[, 1, drop = FALSE]  # the same
sw[, 1]      # a (unnamed) vector
sw[[1]]      # the same

sw[1,]       # a one-row data frame
sw[1,, drop=TRUE]  # a list

swiss[ c(1, 1:2), ]   # duplicate row, unique row names are created

sw[sw <= 6] <- 6  # logical matrix indexing
sw

## adding a column
sw["new1"] <- LETTERS[1:5]   # adds a character column
sw[["new2"]] <- letters[1:5] # ditto
sw[, "new3"] <- LETTERS[1:5] # ditto
sw$new4 <- 1:5
sapply(sw, class)
sw$new4 <- NULL              # delete the column
sw
sw[6:8] <- list(letters[10:14], NULL, aa=1:5) # delete col7, update 6, append
sw

## matrices in a data frame
A <- data.frame(x=1:3, y=I(matrix(4:6)), z=I(matrix(letters[1:9],3,3)))
A[1:3, "y"] # a matrix
A[1:3, "z"] # a matrix
A[, "y"]    # a matrix


Extract or Replace Parts of a Factor

Description

Extract or replace subsets of factors.

Usage

x[..., drop = FALSE]

x[[i]]

x[...] <- value

Arguments

x | a factor
..., i | a specification of indices – see Extract.
drop | logical. If true, unused levels are dropped.
value | character: a set of levels. Factor values are coerced to character.

Details

When unused levels are dropped the ordering of the remaining levels is preserved.

If value is not in levels(x), a missing value is assigned with a warning.

Any contrasts assigned to the factor are preserved unless drop=TRUE.

Value

A factor with the same set of levels as x unless drop=TRUE. (Prior to R 2.4.0, [[ returned the integer code.)

See Also

factor, Extract.

Examples

## following example(factor)
(ff <- factor(substring("statistics", 1:10, 1:10), levels=letters))
ff[, drop=TRUE]
factor(letters[7:10])[2:3, drop = TRUE]


Maxima and Minima

Description

Returns the (parallel) maxima and minima of the input values.

Usage

max(..., na.rm=FALSE)
min(..., na.rm=FALSE)

pmax(..., na.rm=FALSE)
pmin(..., na.rm=FALSE)

Arguments

... | numeric arguments (see Note).
na.rm | a logical indicating whether missing values should be removed.

Value

max and min return the maximum or minimum of all the values present in their arguments, as integer if all are integer, or as double otherwise.
The minimum and maximum of an empty set are +Inf and -Inf (in this order!) which ensures transitivity, e.g., min(x1, min(x2)) == min(x1, x2). From R version 1.5.0, max(x) == -Inf and min(x) == +Inf whenever length(x) == 0 (after removing missing values if requested).
If na.rm is FALSE an NA value in any of the arguments will cause a value of NA to be returned, otherwise NA values are ignored.
pmax and pmin take several vectors (or matrices) as arguments and return a single vector giving the “parallel” maxima (or minima) of the vectors. The first element of the result is the maximum (minimum) of the first elements of all the arguments, the second element of the result is the maximum (minimum) of the second elements of all the arguments and so on. Shorter vectors are recycled if necessary. If na.rm is FALSE, NA values in the input vectors will produce NA values in the output. If na.rm is TRUE, NA values are ignored. attributes (such as names or dim) are transferred from the first argument (if applicable).
max and min are generic functions: methods can be defined for them individually or via the Summary group generic. For this to work properly, the arguments ... should be unnamed, and dispatch is on the first argument.
By definition the min/max of any vector containing an NaN is NaN, except that the min/max of any vector containing an NA is NA even if it also contains an NaN. Note that max(NA, Inf) == NA even though the maximum would be inf whatever the missing value actually is.

Note

‘Numeric’ arguments are vectors of type integer and numeric, and logical (coerced to integer). For historical reasons, NULL is accepted as equivalent to integer(0).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

range (both min and max) and which.min (which.max) for the arg min, i.e., the location where an extreme value occurs.

Examples

require(stats)
 min(5:1, pi) #-> one number
pmin(5:1, pi) #->  5  numbers

x <- sort(rnorm(100));  cH <- 1.35
pmin(cH, quantile(x)) # no names
pmin(quantile(x), cH) # has names
plot(x, pmin(cH, pmax(-cH, x)), type='b', main= "Huber's function")


Factors

Description

The function factor is used to encode a vector as a factor (the terms ‘category’ and ‘enumerated type’ are also used for factors). If ordered is TRUE, the factor levels are assumed to be ordered. For compatibility with S there is also a function ordered.

is.factor, is.ordered, as.factor and as.ordered are the membership and coercion functions for these classes.

Usage

factor(x = character(), levels = sort(unique.default(x), na.last = TRUE),
       labels = levels, exclude = NA, ordered = is.ordered(x))
ordered(x, ...)

is.factor(x)
is.ordered(x)

as.factor(x)
as.ordered(x)

Arguments

x | a vector of data, usually taking a small number of distinct values.
levels | an optional vector of the values that x might have taken. The default is the set of values taken by x, sorted into increasing order.
labels | either an optional vector of labels for the levels (in the same order as levels after removing those in exclude), or a character string of length 1.
exclude | a vector of values to be excluded when forming the set of levels. This should be of the same type as x, and will be coerced if necessary.
ordered | logical flag to determine if the levels should be regarded as ordered (in the order given).
... | (in ordered(.)): any of the above, apart from ordered itself.

Details

The type of the vector x is not restricted.

Ordered factors differ from factors only in their class, but methods and the model-fitting functions treat the two classes quite differently.

The encoding of the vector happens as follows. First all the values in exclude are removed from levels. If x[i] equals levels[j], then the i-th element of the result is j. If no match is found for x[i] in levels, then the i-th element of the result is set to NA.

Normally the ‘levels’ used as an attribute of the result are the reduced set of levels after removing those in exclude, but this can be altered by supplying labels. This should either be a set of new labels for the levels, or a character string, in which case the levels are that character string with a sequence number appended.

factor(x, exclude=NULL) applied to a factor is a no-operation unless there are unused levels: in that case, a factor with the reduced level set is returned. If exclude is used it should also be a factor with the same level set as x or a set of codes for the levels to be excluded.

The codes of a factor may contain NA. For a numeric x, set exclude=NULL to make NA an extra level ("NA"), by default the last level.

If "NA" is a level, the way to set a code to be missing is to use is.na on the left-hand-side of an assignment. Under those circumstances missing values are printed as <NA>.

is.factor is generic: you can write methods to handle specific classes of objects, see InternalMethods.

Value

factor returns an object of class "factor" which has a set of integer codes the length of x with a "levels" attribute of mode character. If ordered is true (or ordered is used) the result has class c("ordered", "factor").
Applying factor to an ordered or unordered factor returns a factor (of the same type) with just the levels which occur: see also [.factor for a more transparent way to achieve this.
is.factor returns TRUE or FALSE depending on whether its argument is of type factor or not. Correspondingly, is.ordered returns TRUE when its argument is ordered and FALSE otherwise.
as.factor coerces its argument to a factor. It is an abbreviated form of factor.
as.ordered(x) returns x if this is ordered, and ordered(x) otherwise.

Warning

The interpretation of a factor depends on both the codes and the "levels" attribute. Be careful only to compare factors with the same set of levels (in the same order). In particular, as.numeric applied to a factor is meaningless, and may happen by implicit coercion. To “revert” a factor f to its original numeric values, as.numeric(levels(f))[f] is recommended and slightly more efficient than as.numeric(as.character(f)).

The levels of a factor are by default sorted, but the sort order may well depend on the locale at the time of creation, and should not be assumed to be ASCII.

Comparison operators and group generic methods

There are "factor" and "ordered" methods for the group generic Ops, which provide methods for the Comparison operators. (The rest of the group and the Math and Summary groups generate an error as they are not meaningful for factors.)

Only == and != can be used for factors: a factor can only be compared to another factor with an identical set of levels (not necessarily in the same ordering) or to a character vector. Ordered factors are compared in the same way, but the general dispatch mechanism precludes comparing ordered and unordered factors.

All the comparison operators are available for ordered factors. Sorting is done by the levels of the operands: if both operands are ordered factors they must have the same level set.

Note

Storing character data as a factor is more efficient storage if there is even a small proportion of repeats. On a 32-bit machine storing a string of n bytes takes 28 + 8*ceiling((n+1)/8) bytes whereas storing a factor code takes 4 bytes. (On a 64-bit machine 28 is replaced by 56 or more.) Only if they were computed from the same values (or in some cases read from a file: see scan) will identical strings share storage.

References

Chambers, J. M. and Hastie, T. J. (1992) Statistical Models in S. Wadsworth & Brooks/Cole.

See Also

[.factor for subsetting of factors.

gl for construction of “balanced” factors and C for factors with specified contrasts. levels and nlevels for accessing the levels, and unclass to get integer codes.

Examples

(ff <- factor(substring("statistics", 1:10, 1:10), levels=letters))
as.integer(ff)  # the internal codes
factor(ff)      # drops the levels that do not occur
ff[, drop=TRUE] # the same, more transparently

factor(letters[1:20], label="letter")

class(ordered(4:1)) # "ordered", inheriting from "factor"

## suppose you want "NA" as a level, and to allowing missing values.
(x <- factor(c(1, 2, "NA"), exclude = ""))
is.na(x)[2] <- TRUE
x  # [1] 1    <NA> NA, <NA> used because NA is a level.
is.na(x)
# [1] FALSE  TRUE FALSE
factor()


Ascertain File Accessibility

Description

Utility function to access information about files on the user's file systems.

Usage

file.access(names, mode = 0)

Arguments

names | character vector containing file names.
mode | integer specifying access mode required.

Details

The mode value can be the exclusive or of the following values

0
test for existence.
1
test for execute permission.
2
test for write permission.
4
test for read permission.

Execute permission is ignored (always granted) under Windows, and all directories have both read and write permissions.

Please note that it is not good to use this function to test before trying to open a file. On a multi-tasking system, it is possible that the accessibility of a file will change between the time you call file.access() and the time you try to open the file, and in recent Windows versions the underlying function in msvcrt.dll sometimes returns inaccurate values. It is better to wrap file open attempts in try instead.

Value

An integer vector with values 0 for success and -1 for failure.

Note

This is intended as a replacement for the S-PLUS function access, a wrapper for the C function of the same name, which explains the return value encoding. Note that the return value is false for success.

See Also

file.info, try

Examples

fa <- file.access(dir("."))
table(fa) # count successes & failures


Choose a File Interactively

Description

Choose a file interactively.

Usage

file.choose(new = FALSE)

Arguments

new Logical: choose the style of dialog box presented to the user: at present only new = FALSE is used.

Value

A character vector of length one giving the file path.

See Also

list.files for non-interactive selection. choose.files for selecting multiple files interactively.


Extract File Information

Description

Utility function to extract information about files on the user's file systems.

Usage

file.info(...)

Arguments

... character vectors containing file names.

Details

What is meant by “file access” and hence the last access time is system-dependent.

File modes are probably only useful on Windows NT/2000/XP machines.

Value

A data frame with row names the file names and columns

size | double: File size in bytes.
isdir | logical: Is the file a directory?
mode | integer of class "octmode". The file permissions, printed in octal, for example 644.
mtime, ctime, atime | integer of class "POSIXct": file modification, creation and last access times.

Entries for non-existent or non-readable files will be NA.

Note

This function will only be operational on systems with the stat system call, but that seems very widely available.

Some (broken) systems allow files of more than 2Gb to be created but not accessed by the stat system call. Such files will show up as non-readable (and very likely not be readable by any of R's input functions).

See Also

files, file.access, list.files, and DateTimeClasses for the date formats.

Examples

ncol(finf <- file.info(dir()))# at least six
## Not run: finf # the whole list
## Those that are more than 100 days old :
finf[difftime(Sys.time(), finf[,"mtime"], units="days") > 100 , 1:4]

file.info("no-such-file-exists")


Construct Path to File

Description

Construct the path to a file from components in a platform-independent way.

Usage

file.path(..., fsep = .Platform$file.sep)

Arguments

... | character vectors.
fsep | the path separator to use.

Value

A character vector of the arguments concatenated term-by-term and separated by fsep if all arguments have positive length; otherwise, an empty character vector.

Note

The components are separated by / (not \) on Windows.


Display One or More Files

Description

Display one or more files.

Usage

file.show(..., header = rep("",nfiles), title = "R Information",
          delete.file=FALSE, pager=getOption("pager"))

Arguments

... | one or more character vectors containing the names of the files to be displayed.
header | character vector (of the same length as the number of files specified in ...) giving a header for each file being displayed. Defaults to empty strings.
title | an overall title for the display. If a single separate window is used for the display, title will be used as the window title. If multiple windows are used, their titles should combine the title and the file-specific header.
delete.file | should the files be deleted after display? Used for temporary files.
pager | the pager to be used.

Details

This function provides the core of the R help system, but it can be used for other purposes as well.

Note

How the pager is implemented is highly system dependent.

The basic Unix version concatenates the files (using the headers) to a temporary file, and displays it in the pager selected by the pager argument, which is a character vector specifying a system command to run on the set of files.

Most GUI systems will use a separate pager window for each file, and let the user leave it up while R continues running. The selection of such pagers could either be done using “magic” pager names being intercepted by lower-level code (such as "internal" and "console" on Windows), or by letting pager be an R function which will be called with the same arguments as file.show and take care of interfacing to the GUI.

Not all implementations will honour delete.file. In particular, using an external pager on Windows does not, as there is no way to know when the external application has finished with the file.

Author(s)

Ross Ihaka, Brian Ripley.

See Also

files, list.files, help.

Examples

file.show(file.path(R.home("doc"), "COPYRIGHTS"))


File and Directory Manipulation

Description

These functions provide a low-level interface to the computer's file system.

Usage

file.create(...)
file.exists(...)
file.remove(...)
file.rename(from, to)
file.append(file1, file2)
file.copy(from, to, overwrite = FALSE)
file.symlink(from, to)
dir.create(path, showWarnings = TRUE, recursive = FALSE)

Arguments

..., file1, file2, from, to | character vectors, containing file names.
path | a character vector containing a single path name.
overwrite | logical; should the destination files be overwritten?
showWarnings | logical; should the warnings on failure be shown?
recursive | logical: should elements of the path other than the last be created? If true, like Unix's mkdir -p.

Details

The ... arguments are concatenated to form one character string: you can specify the files separately or as one vector. All of these functions expand path names: see path.expand.

file.create creates files with the given names if they do not already exist and truncates them if they do.

file.exists returns a logical vector indicating whether the files named by its argument exist.

file.remove attempts to remove the files named in its argument.

file.rename attempts to rename a single file. On Windows 9x/ME rename is not atomic, so it is possible that to will be deleted but from will not be renamed.

file.append attempts to append the files named by its second argument to those named by its first. The R subscript recycling rule is used to align names given in vectors of different lengths.

file.copy works in a similar way to file.append but with the arguments in the natural order for copying. Copying to existing destination files is skipped unless overwrite = TRUE. The to argument can specify a single existing directory.

file.symlink makes symbolic links on those Unix-like platforms which support them. The to argument can specify a single existing directory.

dir.create creates the last element of the path, unless recursive = TRUE. As from R 2.2.1 trailing path separators are ignored. On Windows drives are allowed in the path specification, and unless the path is rooted will be interpreted relative to the current directory on that drive.

Value

dir.create and file.rename return a logical, true for success.
The remaining functions return a logical vector indicating which operation succeeded for each of the files attempted.
dir.create will return failure if the directory already exists.

Author(s)

Ross Ihaka, Brian Ripley

See Also

file.info, file.access, file.path, file.show, list.files, unlink, basename, path.expand.

Examples

cat("file A\n", file="A")
cat("file B\n", file="B")
file.append("A", "B")
file.create("A")
file.append("A", rep("B", 10))
if(interactive()) file.show("A")
file.copy("A", "C")
dir.create("tmp")
file.copy(c("A", "B"), "tmp")
list.files("tmp")
unlink("tmp", recursive=TRUE)
file.remove("A", "B", "C")


Find Interval Numbers or Indices

Description

Find the indices of x in vec, where vec must be sorted (non-decreasingly); i.e., if i <- findInterval(x,v), we have v[i[j]] <= x[j] < v[i[j] + 1] where v[0] := - Inf, v[N+1] := + Inf, and N <- length(vec). At the two boundaries, the returned index may differ by 1, depending on the optional arguments rightmost.closed and all.inside.

Usage

findInterval(x, vec, rightmost.closed = FALSE, all.inside = FALSE)

Arguments

x | numeric.
vec | numeric, sorted (weakly) increasingly, of length N, say.
rightmost.closed | logical; if true, the rightmost interval, vec[N-1] .. vec[N] is treated as closed, see below.
all.inside | logical; if true, the returned indices are coerced into {1,...,N-1}, i.e., 0 is mapped to 1 and N to N-1.

Details

The function findInterval finds the index of one vector x in another, vec, where the latter must be non-decreasing. Where this is trivial, equivalent to apply( outer(x, vec, ">="), 1, sum), as a matter of fact, the internal algorithm uses interval search ensuring O(n * log(N)) complexity where n <- length(x) (and N <- length(vec)). For (almost) sorted x, it will be even faster, basically O(n).

This is the same computation as for the empirical distribution function, and indeed, findInterval(t, sort(X)) is identical to n * Fn(t; X[1],..,X[n]) where Fn is the empirical distribution function of X[1],..,X[n].

When rightmost.closed = TRUE, the result for x[j] = vec[N] ( = max(vec)), is N - 1 as for all other values in the last interval.

Value

vector of length length(x) with values in 0:N (and NA) where N <- length(vec), or values coerced to 1:(N-1) iff all.inside = TRUE (equivalently coercing all x values inside the intervals). Note that NAs are propagated from x, and Inf values are allowed in both x and vec.

Author(s)

Martin Maechler

See Also

approx(*, method = "constant") which is a generalization of findInterval(), ecdf for computing the empirical distribution function which is (up to a factor of n) also basically the same as findInterval(.).

Examples

N <- 100
X <- sort(round(rt(N, df=2), 2))
tt <- c(-100, seq(-2,2, len=201), +100)
it <- findInterval(tt, X)
tt[it < 1 | it >= N] # only first and last are outside range(X)


Force Evaluation of an Argument

Description

Forces the evaluation of a function argument.

Usage

force(x)

Arguments

x a formal argument of the enclosing function.

Details

force forces the evaluation of a formal argument. This can be useful if the argument will be captured in a closure by the lexical scoping rules and will later be altered by an explicit assignment or an implicit assignment in a loop or an apply function.

Note

This is semantic sugar: just evaluating the symbol will do the same thing (see the examples).

force does not force the evaluation of other promises. (It works by forcing the promise that is created when the actual arguments of a call are matched to the formal arguments of a closure, the mechanism which implememnts lazy evaluation.)

Examples

f <- function(y) function() y
lf <- vector("list", 5)
for (i in seq(along = lf)) lf[[i]] <- f(i)
lf[[1]]()  # returns 5

g <- function(y) { force(y); function() y }
lg <- vector("list", 5)
for (i in seq(along = lg)) lg[[i]] <- g(i)
lg[[1]]()  # returns 1

## This is identical to
g <- function(y) { y; function() y }


Foreign Function Interface

Description

Functions to make calls to compiled code that has been loaded into R.

Usage

                .C(name, ..., NAOK = FALSE, DUP = TRUE, PACKAGE)
          .Fortran(name, ..., NAOK = FALSE, DUP = TRUE, PACKAGE)
         .External(name, ..., PACKAGE)
             .Call(name, ..., PACKAGE)
.External.graphics(name, ..., PACKAGE)
    .Call.graphics(name, ..., PACKAGE)

Arguments

name | a character string giving the name of a C function or Fortran subroutine, or an object of class "NativeSymbolInfo" or "NativeSymbol" referring to such a name.
... | arguments to be passed to the foreign function.
NAOK | if TRUE then any NA or NaN or Inf values in the arguments are passed on to the foreign function. If FALSE, the presence of NA or NaN or Inf values is regarded as an error.
DUP | if TRUE then arguments are “duplicated” before their address is passed to C or Fortran.
PACKAGE | if supplied, confine the search for the name to the DLL given by this argument (plus the conventional extension, .so, .sl, .dll, ...). This is intended to add safety for packages, which can ensure by using this argument that no other package can override their external symbols. Use PACKAGE="base" for symbols linked in to R.

Details

The functions .C and .Fortran can be used to make calls to C and Fortran code.

.External and .External.graphics can be used to call compiled code that uses R objects in the same way as internal R functions.

.Call and .Call.graphics can be used call compiled code which makes use of internal R objects. The arguments are passed to the C code as a sequence of R objects. It is included to provide compatibility with S version 4.

For details about how to write code to use with .Call and .External, see the chapter on “System and foreign language interfaces” in “Writing R Extensions” in the ‘doc/manual’ subdirectory of the R source tree.

For Windows-specific details on producing the external code, see the “R Installation and Administration” manual.

Value

The functions .C and .Fortran return a list similar to the ... list of arguments passed in, but reflecting any changes made by the C or Fortran code.
.External, .Call, .External.graphics, and .Call.graphics return an R object.
These calls are typically made in conjunction with dyn.load which links DLLs to R.
The .graphics versions of .Call and .External are used when calling code which makes low-level graphics calls. They take additional steps to ensure that the device driver display lists are updated correctly.

Argument types

The mapping of the types of R arguments to C or Fortran arguments in .C or .Fortran is

R | C | Fortran
integer | int * | integer
numeric | double * | double precision
– or – | float * | real
complex | Rcomplex * | double complex
logical | int * | integer
character | char ** | [see below]
raw | unsigned char * | not allowed
list | SEXP * | not allowed
other | SEXP | not allowed

Numeric vectors in R will be passed as type double * to C (and as double precision to Fortran) unless (i) .C or .Fortran is used, (ii) DUP is false and (iii) the argument has attribute Csingle set to TRUE (use as.single or single). This mechanism is only intended to be used to facilitate the interfacing of existing C and Fortran code.

The C type Rcomplex is defined in ‘Complex.h’ as a typedef struct {double r; double i;}. Fortran type double complex is an extension to the Fortran standard, and the availability of a mapping of complex to Fortran may be compiler dependent.

Note: The C types corresponding to integer and logical are int, not long as in S. This difference matters on 64-bit platforms.

The first character string of a character vector is passed as a C character array to Fortran: that string may be usable as character*255 if its true length is passed separately. Only up to 255 characters of the string are passed back. (How well this works, or even if it works at all, depends on the C and Fortran compilers and the platform.)

Missing (NA) string values are passed to .C as the string "NA". As the C char type can represent all possible bit patterns there appears to be no way to distinguish missing strings from the string "NA". If this distinction is important use .Call.

Functions, expressions, environments and other language elements are passed as the internal R pointer type SEXP. This type is defined in ‘Rinternals.h’ or the arguments can be declared as generic pointers, void *. Lists are passed as C arrays of SEXP and can be declared as void * or SEXP *. Note that you cannot assign values to the elements of the list within the C routine. Assigning values to elements of the array corresponding to the list bypasses R's memory management/garbage collection and will cause problems. Essentially, the array corresponding to the list is read-only. If you need to return S objects created within the C routine, use the .Call interface.

R functions can be invoked using call_S or call_R and can be passed lists or the simple types as arguments.

Warning

DUP=FALSE is dangerous.

There are two dangers with using DUP=FALSE.

The first is that if you pass a local variable to .C/.Fortran with DUP=FALSE, your compiled code can alter the local variable and not just the copy in the return list. Worse, if you pass a local variable that is a formal parameter of the calling function, you may be able to change not only the local variable but the variable one level up. This will be very hard to trace.

The second is that lists are passed as a single R SEXP with DUP=FALSE, not as an array of SEXP. This means the accessor macros in ‘Rinternals.h’ are needed to get at the list elements and the lists cannot be passed to call_S/call_R. New code using R objects should be written using .Call or .External, so this is now only a minor issue.

In addition, character vectors and lists cannot be used with DUP=FALSE.

It is safe and useful to set DUP=FALSE if you do not change any of the variables that might be affected, e.g.,

.C("Cfunction", input=x, output=numeric(10)).

In this case the output variable did not exist before the call so it cannot cause trouble. If the input variable is not changed in the C code of Cfunction you are safe.

Neither .Call nor .External copy their arguments. You should treat arguments you receive through these interfaces as read-only.

Fortran symbol names

All compilers that can be used with R map symbol names to lower case, and so does .Fortran.

Symbol names containing underscores are not valid Fortran 77 (although they are valid in Fortran 9x). Many Fortran 77 compilers (including g77) will allow them but translate them in a different way to names not containing underscores. As from R 2.4.0 such names will work with .Fortran, but portable code should not use Fortran names containing underscores.

Use .Fortran with care for compiled Fortran 9x code: it may not work if the Fortran 9x compiler used differs from the Fortran compiler used when configuring R, especially if the subroutine name is not lower-case or includes an underscore.

Header files for external code

Writing code for use with .External and .Call will need to use internal R structures. If possible use just those defined in ‘Rinternals.h’ and/or the macros in ‘Rdefines.h’, as other header files are not installed and are even more likely to be changed.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole. (.C and .Fortran.)

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language. Springer. (.Call.)

See Also

dyn.load.


Access to and Manipulation of the Formal Arguments

Description

Get or set the formal arguments of a function.

Usage

formals(fun = sys.function(sys.parent()))
formals(fun, envir = environment(fun)) <- value

Arguments

fun | a function object, or see Details.
envir | environment in which the function should be defined.
value | a list (or pairlist) of R expressions.

Details

For the first form, fun can also be a character string naming the function to be manipulated, which is searched for from the parent environment. If it is not specified, the function calling formals is used.

Value

formals returns the formal argument list of the function specified, as a pairlist.
The replacment form sets the formals of a function to the list/pairlist on the right hand side, and (potentially) resets the environment of the function.

See Also

args for a “human-readable” version, alist, body, function.

Examples

length(formals(lm))      # the number of formal arguments
names(formals(boxplot))  # formal arguments names

f <- function(x) a+b
formals(f) <- alist(a=,b=3) # function(a,b=3)a+b
f(2) # result = 5


Encode in a Common Format

Description

Format an R object for pretty printing.

Usage

format(x, ...)

## Default S3 method:
format(x, trim = FALSE, digits = NULL, nsmall = 0,
       justify = c("left", "right", "centre", "none"),
       width = NULL, na.encode = TRUE, scientific = NA,
       big.mark = "",   big.interval = 3,
     small.mark = "", small.interval = 5,
   decimal.mark = ".", zero.print = NULL, ...)

## S3 method for class 'data.frame':
format(x, ..., justify = "none")

## S3 method for class 'factor':
format(x, ...)

## S3 method for class 'AsIs':
format(x, width = 12, ...)

Arguments

x | any R object (conceptually); typically numeric.
trim | logical; if FALSE, logical, numeric and complex values are right-justified to a common width: if TRUE the leading blanks for justification are suppressed.
digits | how many significant digits are to be used for numeric and complex x. The default, NULL, uses getOption(digits). This is a suggestion: enough decimal places will be used so that the smallest (in magnitude) number has this many significant digits, and also to satisfy nsmall. (For the intepretation for complex numbers see signif.)
nsmall | the minimum number of digits to the right of the decimal point in formatting real/complex numbers in non-scientific formats. Allowed values are 0 <= nsmall <= 20.
justify | should a character vector be left-justified (the default), right-justified, centred or left alone.
width | default method: the minimum field width or NULL or 0 for no restriction. AsIs method: the maximum field width for non-character objects. NULL corresponds to the default 12.
na.encode | logical: should NA strings be encoded?
scientific | Either a logical specifiying whether elements of a real or complex vector should be encoded in scientific format, or an integer penalty (see options("scipen"). Missing values correspond to the current default penalty.
... | further arguments passed to or from other methods.
big.mark, big.interval, small.mark, small.interval, decimal.mark, zero.print | used for prettying longer decimal sequences, passed to prettyNum: that help page explains the details.

Details

format is a generic function. Apart from the methods described here there are methods for dates (see format.Date), date-times (see format.POSIXct)) and for other classes such as format.octmode and format.dist.

format.data.frame formats the data frame column by column, applying the appropriate method of format for each column. Methods for columns are often similar to as.character but offer more control. Matrix and data-frame columns will be converted to separate columns in the result, and character columns (normally all) will be given class "AsIs".

format.factor converts the factor to a character vector and then calls the default method (and so justify applies).

format.AsIs deals with columns of complicated objects that have been extracted from a data frame. Character objects are passed to the default method (and so width does not apply). Otherwise it calls toString to convert the object to character (if a vector or list, element by element) and then right-justifies the result.

Justification for character vectors (and objects converted to character vectors by their methods) is done on display width (see nchar), taking double-width characters and the rendering of special characters (as escape sequences, including escaping backslash: see print.default) into account. Character strings are padded with blanks to the display width of the widest. (If na.encode = FALSE missing character strings are not included in the width computations and are not encoded.)

Numeric vectors are encoded with the minimum number of decimal places needed to display all the elements to at least the digit significant digits. However, if all the elements then have trailing zeroes, the number of decimal places is reduced until at least one element has a non-zero final digit.

Raw vectors are converted to their 2-digit hexadecimal representation by as.character.

Value

An object of similar structure to x containing character representations of the elements of the first argument x in a common format.
For numeric or complex x, dims and dimnames are preserved on matrices/arrays and names on vectors: no other attributes are copied.
If x is a list, the result is a character vector obtained by applying format.default(x, ...) to each element of the list (after unlisting elements which are themselves lists), and then collapsing the result for each element with paste(collapse = ", "). The defaults in this case are trim = TRUE, justify = "none" since one does not usually want alignment in the collapsed strings.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

format.info indicates how an atomic vector would be formatted.

formatC, paste, as.character, sprintf, print, toString, encodeString.

Examples

format(1:10)
format(1:10, trim = TRUE)

zz <- data.frame("(row names)"= c("aaaaa", "b"), check.names=FALSE)
format(zz)
format(zz, justify = "left")

## use of nsmall
format(13.7)
format(13.7, nsmall = 3)
format(c(6.0, 13.1), digits = 2)
format(c(6.0, 13.1), digits = 2, nsmall = 1)

## use of scientific
format(2^31-1)
format(2^31-1, sci = TRUE)

## a list
z <- list(a=letters[1:3], b=(-pi+0i)^((-2:2)/2), c=c(1,10,100,1000),
          d=c("a", "longer", "character", "string"))
format(z, digits = 2)
format(z, digits = 2, justify = "left", trim = FALSE)


Date Conversion Functions to and from Character

Description

Functions to convert between character representations and objects of class "Date" representing calendar dates.

Usage

as.Date(x, ...)
## S3 method for class 'character':
as.Date(x, format = "", ...)

## S3 method for class 'Date':
format(x, ...)

## S3 method for class 'Date':
as.character(x, ...)

Arguments

x | An object to be converted.
format | A character string. The default is "%Y-%m-%d". For details see strftime.
... | Further arguments to be passed from or to other methods, including format for as.character and as.Date methods.

Details

The usual vector re-cycling rules are applied to x and format so the answer will be of length that of the longer of the vectors.

Locale-specific conversions to and from character strings are used where appropriate and available. This affects the names of the days and months.

The as.Date methods accept character strings, factors, logical NA and objects of classes "POSIXlt" and "POSIXct". (The last are converted to days by ignoring the time after midnight in the representation of the time in UTC.) Also objects of class "date" (from package date or survival) and "dates" (from package chron).

See the examples for how to convert a day given as the number of days since an epoch.

The format and as.character methods ignore any fractional part of the date.

Value

The format and as.character methods return a character vector representing the date.
The as.Date methods return an object of class "Date".

Note

The default formats follow the rules of the ISO 8601 international standard which expresses a day as "2001-02-03".

If the date string does not specify the date completely, the returned answer may be system-specific. The most common behaviour is to assume that a missing year, month or day is the current one. If it specifies a date incorrectly, reliable implementations will give an error and the date is reported as NA. Unfortunately some common implementations (such as glibc) are unreliable and guess at the intended meaning.

Years before 1CE (aka 1AD) will probably not be handled correctly.

References

International Organization for Standardization (2004, 1988, 1997, ...) ISO 8601. Data elements and interchange formats – Information interchange – Representation of dates and times. For links to versions available on-line see (at the time of writing) http://www.qsl.net/g1smd/isopdf.htm; for information on the current official version, see http://www.iso.org/iso/en/prods-services/popstds/datesandtime.html.

See Also

Date for details of the date class; locales to query or set a locale.

Your system's help pages on strftime and strptime to see how to specify their formats. Windows users will find no help page for strptime: code based on glibc is used (with corrections), so all the format specifiers described here are supported, but with no alternative number representation nor era available in any locale.

Examples

## locale-specific version of the date
format(Sys.Date(), "%a %b %d")

## read in date info in format 'ddmmmyyyy'
## This will give NA(s) in some locales; setting the C locale
## as in the commented lines will overcome this on most systems.
## lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C")
x <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
z <- as.Date(x, "%d%b%Y")
## Sys.setlocale("LC_TIME", lct)
z

## read in date/time info in format 'm/d/y'
dates <- c("02/27/92", "02/27/92", "01/14/92", "02/28/92", "02/01/92")
as.Date(dates, "%m/%d/%y")

## date given as number of days since 1900-01-01 (a date in 1989)
as.Date("1900-01-01") + 32768


format(.) Information

Description

Information is returned on how format(x, digits, nsmall) would be formatted.

Usage

format.info(x, digits = NULL, nsmall = 0)

Arguments

x | an atomic vector; a potential argument of format(x, ...).
digits | how many significant digits are to be used for numeric and complex x. The default, NULL, uses getOption(digits).
nsmall | (see format(..., nsmall)).

Value

An integer vector of length 1, 3 or 6, say r.
For logical, integer and character vectors a single element, the width which would be used by format if width = NULL.
For numeric vectors:

r[1] | width (in characters) used by format(x)
r[2] | number of digits after decimal point.
r[3] | in 0:2; if >=1, exponential representation would be used, with exponent length of r[3]+1.

For a complex vector the first three elements refer to the real parts, and there are three further elements corresponding to the imaginary parts.

See Also

format, formatC.

Examples

dd <- options("digits") ; options(digits = 7) #-- for the following
format.info(123)   # 3 0 0
format.info(pi)    # 8 6 0
format.info(1e8)   # 5 0 1 - exponential "1e+08"
format.info(1e222) # 6 0 2 - exponential "1e+222"

x <- pi*10^c(-10,-2,0:2,8,20)
names(x) <- formatC(x,w=1,dig=3,format="g")
cbind(sapply(x,format))
t(sapply(x, format.info))

## using at least 8 digits right of "."
t(sapply(x, format.info, nsmall = 8))

# Reset old options:
options(dd)


Format P Values

Description

format.pval is intended for formatting p-values.

Usage

format.pval(pv, digits = max(1, getOption("digits") - 2),
            eps = .Machine$double.eps, na.form = "NA")

Arguments

pv | a numeric vector.
digits | how many significant digits are to be used.
eps | a numerical tolerance: see Details.
na.form | character representation of NAs.

Details

format.pval is mainly an auxiliary function for print.summary.lm etc., and does separate formatting for fixed, floating point and very small values; those less than eps are formatted as "< [eps]" (where “[eps]” stands for format(eps, digits)).

Value

A character vector.

Examples

format.pval(c(runif(5), pi^-100, NA))
format.pval(c(0.1, 0.0001, 1e-27))


Formatting Using C-style Formats

Description

Formatting numbers individually and flexibly, using C style format specifications.

Usage

formatC(x, digits = NULL, width = NULL,
        format = NULL, flag = "", mode = NULL,
        big.mark = "", big.interval = 3,
      small.mark = "", small.interval = 5,
    decimal.mark = ".", preserve.width = "individual")

prettyNum(x, big.mark = "",   big.interval = 3,
          small.mark = "", small.interval = 5,
          decimal.mark = ".",
          preserve.width = c("common", "individual", "none"),
          zero.print = NULL, ...)

Arguments

x | an atomic numerical or character object, typically a vector of real numbers.
digits | the desired number of digits after the decimal point (format = "f") or significant digits (format = "g", = "e" or = "fg"). Default: 2 for integer, 4 for real numbers. If less than 0, the C default of 6 digits is used.
width | the total field width; if both digits and width are unspecified, width defaults to 1, otherwise to digits + 1. width = 0 will use width = digits, width < 0 means left justify the number in this field (equivalent to flag ="-"). If necessary, the result will have more characters than width.
format | equal to "d" (for integers), "f", "e", "E", "g", "G", "fg" (for reals), or "s" (for strings). Default is "d" for integers, "g" for reals. "f" gives numbers in the usual xxx.xxx format; "e" and "E" give n.ddde+nn or n.dddE+nn (scientific format); "g" and "G" put x[i] into scientific format only if it saves space to do so. "fg" uses fixed format as "f", but digits as the minimum number of significant digits. That this can lead to quite long result strings, see examples below. Note that unlike signif this prints large numbers with more significant digits than digits.
flag | For formatC, a character string giving a format modifier as in Kernighan and Ritchie (1988, page 243). "0" pads leading zeros; "-" does left adjustment, others are "+", " ", and "#". There can be more than one of these, in any order.
mode | "double" (or "real"), "integer" or "character". Default: Determined from the storage mode of x.
big.mark | character; if not empty used as mark between every big.interval decimals before (hence big) the decimal point.
big.interval | see big.mark above; defaults to 3.
small.mark | character; if not empty used as mark between every small.interval decimals after (hence small) the decimal point.
small.interval | see small.mark above; defaults to 5.
decimal.mark | the character to be used to indicate the numeric decimal point.
preserve.width | string specifying if the string widths should be preserved where possible in those cases where marks (big.mark or small.mark) are added. "common", the default, corresponds to format-like behavior whereas "individual" is the default in formatC().
zero.print | logical, character string or NULL specifying if and how zeros should be formatted specially. Useful for pretty printing “sparse” objects.
... | arguments passed to format.

Details

If you set format it overrides the setting of mode, so formatC(123.45, mode="double", format="d") gives 123.

The rendering of scientific format is platform-dependent: some systems use n.ddde+nnn or n.dddenn rather than n.ddde+nn.

formatC does not necessarily align the numbers on the decimal point, so formatC(c(6.11, 13.1), digits=2, format="fg") gives c("6.1", " 13"). If you want common formatting for several numbers, use format.

prettyNum is the utility function for prettifying x. If x is not a character, format(x[i], ...) is applied to each element, and then it is left unchanged if all the other arguments are at their defaults. Note that prettyNum(x) may behave unexpectedly if x is a character vector not resulting from something like format(<number>): in particular it assumes that a period is a decimal mark.

Value

A character object of same size and attributes as x. Unlike format, each number is formatted individually. Looping over each element of x, the C function sprintf(...) is called (inside the C function str_signif).
formatC: for character x, do simple (left or right) padding with white space.

Author(s)

formatC was originally written by Bill Dunlap, later much improved by Martin Maechler. It was first adapted for R by Friedrich Leisch.

References

Kernighan, B. W. and Ritchie, D. M. (1988) The C Programming Language. Second edition. Prentice Hall.

See Also

format.

sprintf for more general C like formatting.

Examples

xx  <- pi * 10^(-5:4)
cbind(format(xx, digits=4), formatC(xx))
cbind(formatC(xx, wid = 9, flag = "-"))
cbind(formatC(xx, dig = 5, wid = 8, format = "f", flag = "0"))
cbind(format(xx, digits=4), formatC(xx, dig = 4, format = "fg"))

formatC(    c("a", "Abc", "no way"), wid = -7)  # <=> flag = "-"
formatC(c((-1:1)/0,c(1,100)*pi), wid=8, dig=1)

xx <- c(1e-12,-3.98765e-10,1.45645e-69,1e-70,pi*1e37,3.44e4)
##       1        2             3        4      5       6
formatC(xx)
formatC(xx, format="fg")       # special "fixed" format.
formatC(xx, format="f", dig=80)#>> also long strings

r <- c("76491283764.97430", "29.12345678901", "-7.1234", "-100.1","1123")
## American:
prettyNum(r, big.mark = ",")
## Some Europeans:
prettyNum(r, big.mark = "'", decimal.mark = ",")

(dd <- sapply(1:10, function(i)paste((9:0)[1:i],collapse="")))
prettyNum(dd, big.mark="'")

## examples of 'small.mark'
pN <- stats::pnorm(1:7, lower=FALSE)
cbind(format (pN, small.mark = " ", digits = 15))
cbind(formatC(pN, small.mark = " ", digits = 17, format = "f"))

cbind(ff <- format(1.2345 + 10^(0:5), width = 11, big.mark = "'"))
## all with same width (one more than the specified minimum)

## individual formatting to common width:
fc <- formatC(1.234 + 10^(0:8), format="fg", width=11, big.mark = "'")
cbind(fc)


Format Description Lists

Description

Format vectors of items and their descriptions as 2-column tables or LaTeX-style description lists.

Usage

formatDL(x, y, style = c("table", "list"),
         width = 0.9 * getOption("width"), indent = NULL)

Arguments

x | a vector giving the items to be described, or a list of length 2 or a matrix with 2 columns giving both items and descriptions.
y | a vector of the same length as x with the corresponding descriptions. Only used if x does not already give the descriptions.
style | a character string specifying the rendering style of the description information. If "table", a two-column table with items and descriptions as columns is produced (similar to Texinfo's @table environment. If "list", a LaTeX-style tagged description list is obtained.
width | a positive integer giving the target column for wrapping lines in the output.
indent | a positive integer specifying the indentation of the second column in table style, and the indentation of continuation lines in list style. Must not be greater than width/2, and defaults to width/3 for table style and width/9 for list style.

Details

After extracting the vectors of items and corresponding descriptions from the arguments, both are coerced to character vectors.

In table style, items with more than indent - 3 characters are displayed on a line of their own.

Value

a character vector with the formatted entries.

Examples

## Use R to create the 'INDEX' for package 'splines' from its 'CONTENTS'
x <- read.dcf(file = system.file("CONTENTS", package = "splines"),
               fields = c("Entry", "Description"))
x <- as.data.frame(x)
writeLines(formatDL(x$Entry, x$Description))
## or equivalently: writeLines(formatDL(x))
## Same information in tagged description list style:
writeLines(formatDL(x$Entry, x$Description, style = "list"))
## or equivalently: writeLines(formatDL(x, style = "list"))


Function Definition

Description

These functions provide the base mechanisms for defining new functions in the R language.

Usage

function( arglist ) expr
return(value)

Arguments

arglist | Empty or one or more name or name=expression terms.
value | An expression.

Details

In R (unlike S) the names in an argument list cannot be quoted non-standard names.

If value is missing, NULL is returned. If it is a single expression, the value of the evaluated expression is returned.

If the end of a function is reached without calling return, the value of the last evaluated expression is returned.

Warning

Prior to R 1.8.0, value could be a series of non-empty expressions separated by commas. In that case the value returned is a list of the evaluated expressions, with names set to the expressions where these are the names of R objects. That is, a=foo() names the list component a and gives it value the result of evaluating foo().

This has been deprecated (and a warning is given), as it was never documented in S, and whether or not the list is named differs by S versions.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

args and body for accessing the arguments and body of a function.

debug for debugging; using invisible inside return(.) for returning invisibly.

Examples

norm <- function(x) sqrt(x%*%x)
norm(1:4)

## An anonymous function:
(function(x,y){ z <- x^2 + y^2; x+y+z })(0:7, 1)


Garbage Collection

Description

A call of gc causes a garbage collection to take place. gcinfo sets a flag so that automatic collection is either silent (verbose=FALSE) or prints memory usage statistics (verbose=TRUE).

Usage

gc(verbose = getOption("verbose"), reset=FALSE)
gcinfo(verbose)

Arguments

verbose | logical; if TRUE, the garbage collection prints statistics about cons cells and the space allocated for vectors.
reset | logical; if TRUE the values for maximum space used are reset to the current values.

Details

A call of gc causes a garbage collection to take place. This will also take place automatically without user intervention, and the primary purpose of calling gc is for the report on memory usage.

However, it can be useful to call gc after a large object has been removed, as this may prompt R to return memory to the operating system.

R allocates space for vectors in multiples of 8 bytes: hence the report of "Vcells", a relict of an earlier allocator (that used a vector heap).

Value

gc returns a matrix with rows "Ncells" (cons cells), usually 28 bytes each on 32-bit systems and 56 bytes on 64-bit systems, and "Vcells" (vector cells, 8 bytes each), and columns "used" and "gc trigger", each also interpreted in megabytes (rounded up to the next 0.1Mb).
If maxima have been set for either "Ncells" or "Vcells", a fifth column is printed giving the current limits in Mb (with NA denoting no limit).
The final two columns show the maximum space used since the last call to gc(reset=TRUE) (or since R started).
gcinfo returns the previous value of the flag.

See Also

Memory on R's memory management, and gctorture if you are an R hacker.

reg.finalizer for actions to happen at garbage collection.

Examples

gc() #- do it now
gcinfo(TRUE) #-- in the future, show when R does it
x <- integer(100000); for(i in 1:18) x <- c(x,i)
gcinfo(verbose = FALSE)#-- don't show it anymore

gc(TRUE)

gc(reset=TRUE)


Report Time Spent in Garbage Collection

Description

This function reports the time spent in garbage collection so far in the R session while GC timing was enabled..

Usage

gc.time(on = TRUE)

Arguments

on logical; if TRUE, GC timing is enabled.

Value

A numerical vector of length 5 giving the user CPU time, the system CPU time, the elapsed time and children's user and system CPU times (normally both zero).

Warnings

This is experimental functionality, likely to be removed as soon as the next release.

The timings are rounded up by the sampling interval for timing processes, and so are likely to be over-estimates.

Note

CPU times will be returned as NA on Windows 9x/ME systems, but are genuine times on NT4/2000/XP systems. Times of child processes are not available and will always be given as NA.

See Also

gc, proc.time for the timings for the session.

Examples

gc.time()


Torture Garbage Collector

Description

Provokes garbage collection on (nearly) every memory allocation. Intended to ferret out memory protection bugs. Also makes R run very slowly, unfortunately.

Usage

gctorture(on = TRUE)

Arguments

on logical; turning it on/off.

Value

Previous value.

Author(s)

Peter Dalgaard


Return the Value of a Named Object

Description

Search for an R object with a given name and return it.

Usage

get(x, pos = -1, envir = as.environment(pos), mode = "any",
    inherits = TRUE)

mget(x, envir, mode = "any",
     ifnotfound = list(function(x) stop(paste("value for '",
     x, "' not found", sep = ""), call. = FALSE)), inherits = FALSE)

Arguments

x | a variable name (given as a character string).
pos | where to look for the object (see the details section); if omitted, the function will search as if the name of the object appeared unquoted in an expression.
envir | an alternative way to specify an environment to look in; see the Details section.
mode | the mode or type of object sought: see the Details section.
inherits | should the enclosing frames of the environment be searched?
ifnotfound | A list of values to be used if the item is not found: it will be coerced to list if necessary.

Details

The pos argument can specify the environment in which to look for the object in any of several ways: as an integer (the position in the search list); as the character string name of an element in the search list; or as an environment (including using sys.frame to access the currently active function calls). The envir argument is an alternative way to specify an environment, but is primarily there for back compatibility.

This function looks to see if the name x has a value bound to it in the specified environment. If inherits is TRUE and a value is not found for x in the specified environment, the enclosing frames of the environment are searched until the name x is encountered. See environment and the ‘R Language Definition’ manual for details about the structure of environments and their enclosures.

Warning: inherits = TRUE is the default behaviour for R but not for S.

If mode is specified then only objects of that type are sought. The mode may specify one of the collections "numeric" and "function" (see mode): any member of the collection will suffice.

Using a NULL environment is equivalent to using the current environment.

For mget multiple values are returned in a named list. This is true even if only one value is requested. The value in mode and ifnotfound can be either the same length as the number of requested items or of length 1. The argument ifnotfound must be a list containing either the value to use if the requested item is not found or a function of one argument which will be called if the item is not found, with argument the name of the item being requested. The default value for inherits is FALSE, in contrast to the default behavior for get.

mode here is a mixture of the meanings of typeof and mode: "function" covers primitive functions and operators, "numeric", "integer", "real" and "double" all refer to any numeric type, "symbol" and "name" are equivalent but "language" must be used.

Value

The object found. (If no object is found an error results.)

Note

The reverse of a <- get(nam) is assign(nam, a).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

exists, assign.

Examples

get("%o%")

##test mget
e1 <- new.env()
mget(letters, e1, ifnotfound = as.list(LETTERS))


Compute DLL for native interface call

Description

This is an internal function that is called from R's C code to determine the enclosing namespace of a .C/.Call/.Fortran/.External call which has no PACKAGE argument. If the call has been made from a function within a namespace, then we can find the DLL associated with that namespace. The purpose of this is to avoid having to use the PACKAGE argument in these native calls and so better support versions of packages.

This is an internal function that may be migrated to internal C code in the future and so should not be used by R programmers.

Usage

getCallingDLL(f = sys.function(-1), doStop = FALSE)
getCallingDLLe(e)

Arguments

f | the function whose namespace and DLL are to be found. By default, this is the current function being called which is the one in which the native routine is being invoked.
doStop | a logical value indicating whether failure to find a namespace and/or DLL is an error (TRUE) or not (FALSE). The default is FALSE so that when this is called because there is no PACKAGE argument in a .C, .Call, .Fortran, .External call, no error occurs and the regular lookup is performed by searching all DLLs in order.
e | an environment.

See Also

.C, .Call, .Fortran, .External

Examples

if(exists("ansari.test"))
   getCallingDLL(ansari.test)


Reflectance Information for C/Fortran routines in a DLL

Description

This function allows us to query the set of routines in a DLL that are registered with R to enhance dynamic lookup, error handling when calling native routines, and potentially security in the future. This function provides a description of each of the registered routines in the DLL for the different interfaces, i.e. .C, .Call, .Fortran and .External.

Usage

getDLLRegisteredRoutines(dll, addNames = TRUE)

Arguments

dll | a character string or DLLInfo object (as returned by getLoadedDLLs).
addNames | a logical value. If this is TRUE, the elements of the returned lists are named using the names of the routines (as seen by R via registration or raw name). If FALSE, these names are not computed and assigned to the lists. As a result, the call should be quicker. The name information is also available in the NativeSymbolInfo objects in the lists.

Details

This takes the registration information after it has been registered and processed by the R internals. In other words, it uses the extended information

Value

A list with four elements corresponding to the routines registered for the .C, .Call, .Fortran and .External interfaces. Each element is a list with as many elements as there were routines registered for that interface. Each element identifies a routine and is an object of class NativeSymbolInfo. An object of this class has the following fields:

name | the registered name of the routine (not necessarily the name in the C code).
address | the memory address of the routine as resolved in the loaded DLL. This may be NULL if the symbol has not yet been resolved.
dll | an object of class DLLInfo describing the DLL. This is same for all elements returned.
numParameters | the number of arguments the native routine is to be called with. In the future, we will provide information about the types of the parameters also.

Author(s)

Duncan Temple Lang <duncan@wald.ucdavis.edu>

References

"Writing R Extensions Manual" for symbol registration. R News, Volume 1/3, September 2001. "In search of C/C++ & Fortran Symbols"

See Also

getLoadedDLLs

Examples

dlls <- getLoadedDLLs()
getDLLRegisteredRoutines(dlls[["base"]])

getDLLRegisteredRoutines("stats")


Get Environment Variables

Description

Sys.getenv obtains the values of the environment variables named by x.

Usage

Sys.getenv(x)

Arguments

x a character vector, or missing

Value

A vector of the same length as x, with the variable names as its names attribute. Each element holds the value of the environment variable named by the corresponding component of x (or "" if no environment variable with that name was found).
On most platforms Sys.getenv() will return a named vector giving the values of all the environment variables.

See Also

Sys.putenv, Sys.getlocale for the locale “environment”, getwd for the working directory.

Examples

## whether HOST is set will be shell-dependent e.g. Solaris' csh does not.
Sys.getenv(c("R_HOME", "R_PAPERSIZE", "R_PRINTCMD", "HOST"))

str(s <- Sys.getenv()) # all settings (rather do not print)

## Language and Locale settings -- but rather use Sys.getlocale()
s[grep("^L(C|ANG)", names(s))]


Get DLLs Loaded in Current Session

Description

This function provides a way to get a list of all the Dynamically Loadable Libraries (DLLs) that are currently loaded in the current R session.

Usage

getLoadedDLLs()

Details

This queries the internal table that manages the DLLs.

Value

An object of class "DLLInfoList" which is a list with an element corresponding to each DLL that is currently loaded in the session. Each element is an object of class "DLLInfo" which has the following entries.

name | the abbreviated name.
path | the fully qualified name of the file which was dynamically loaded.
dynamicLookup | a logical value indicating whether R uses only the registration information to resolve symbols or whether it searches the entire symbol table of the DLL.
handle | a reference to the C-level data structure that provides access to the contents of the DLL. This is an object of class "DLLHandle".

Note that the class DLLInfo has an overloaded method for $ which can be used to resolve native symbols within that DLL. Therefore, one must access the R-level elements described above using [[, e.g. x[["name"]] or x[["handle"]].

Note

We are starting to use the handle elements in the DLL object to resolve symbols more directly in R.

Author(s)

Duncan Temple Lang duncan@wald.ucdavis.edu.

See Also

getDLLRegisteredRoutines, getNativeSymbolInfo

Examples

getLoadedDLLs()


Obtain a Description of one or more Native (C/Fortran) Symbols

Description

This finds and returns as comprehensive a description of one or more dynamically loaded or “exported” built-in native symbols. For each name, it returns information about the name of the symbol, the library in which it is located and, if available, the number of arguments it expects and by which interface it should be called (i.e .Call, .C, .Fortran, or .External). Additionally, it returns the address of the symbol and this can be passed to other C routines which can invoke. Specifically, this provides a way to explicitly share symbols between different dynamically loaded package libraries. Also, it provides a way to query where symbols were resolved, and aids diagnosing strange behavior associated with dynamic resolution.

This is now vectorized in the name argument so can process multiple symbols in a single call. The result is a list that can be indexed by the given symbol names.

Usage

getNativeSymbolInfo(name, PACKAGE, unlist = TRUE,
                    withRegistrationInfo = FALSE)

Arguments

name | the name(s) of the native symbol(s) as used in a call to is.loaded, etc. Note that Fortran symbols should be supplied as-is, not wrapped in symbol.For.
PACKAGE | an optional argument that specifies to which dynamically loaded library we restrict the search for this symbol. If this is "base", we search in the R executable itself.
unlist | a logical value which controls how the result is returned if the function is called with the name of a single symbol. If unlist is TRUE and the number of symbol names in name is one, then the NativeSymbolInfo object is returned. If it is FALSE, then a list of NativeSymbolInfo objects is returned. This is ignored if the number of symbols passed in name is more than one. To be compatible with earlier versions of this function, this defaults to TRUE.
withRegistrationInfo | a logical value indicating whether, if TRUE, to return information that was registered with R about the symbol and its parameter types if such information is available, or if FALSE to return the address of the symbol.

Details

This uses the same mechanism for resolving symbols as is used in all the native interfaces (.Call, etc.). If the symbol has been explicitly registered by the shared library in which it is contained, information about the number of arguments and the interface by which it should be called will be returned. Otherwise, a generic native symbol object is returned.

Value

Generally, a list of NativeSymbolInfo elements whose elements can be indexed by the elements of name in the call. Each NativeSymbolInfo object is a list containing the following elements:

name | the name of the symbol, as given by the name argument.
address | if withRegistrationInfo is FALSE, this is the native memory address of the symbol which can be used to invoke the routine, and also to compare with other symbol addresses. This is an external pointer object and of class NativeSymbol. If withRegistrationInfo is TRUE and registration information is available for the symbol, then this is an object of class RegisteredNativeSymbol and is a reference to an internal data type that has access to the routine pointer and registration information. This too can be used in calls to .Call, .C, .Fortran and .External.
package a list containing 3 elements:
name
the short form of the library name which can be used as the value of the PACKAGE argument in the different native interface functions.
path
the fully qualified name of the shared library file.
dynamicLookup
a logical value indicating whether dynamic resolution is used when looking for symbols in this library, or only registered routines can be located.
numParameters | the number of arguments that should be passed in a call to this routine.

Additionally, the list will have an additional class, being CRoutine, CallRoutine, FortranRoutine or ExternalRoutine corresponding to the R interface by which it should be invoked.
If any of the symbols is not found, an error is immediately raised.
If name contains only one symbol name and unlist is TRUE, then the single NativeSymbolInfo is returned rather than the list containing that one element.

Note

One motivation for accessing this reflectance information is to be able to pass native routines to C routines as “function pointers” in C. This allows us to treat native routines and R functions in a similar manner, such as when passing an R function to C code that makes callbacks to that function at different points in its computation (e.g., nls). Additionally, we can resolve the symbol just once and avoid resolving it repeatedly or using the internal cache. In the future, one may be able to treat NativeSymbol objects directly as callback objects.

Author(s)

Duncan Temple Lang

References

For information about registering native routines, see “In Search of {C/C++} & {FORTRAN} Routines”, R News, volume 1, number 3, 2001, p20–23 (http://CRAN.R-project.org/doc/Rnews/).

See Also

getDLLRegisteredRoutines, is.loaded, .C, .Fortran, .External, .Call, dyn.load.

Examples

library(stats) # normally loaded
getNativeSymbolInfo("dansari")

getNativeSymbolInfo("hcass2")  # a Fortran symbol


Get the Process ID of the R Session

Description

Get the process ID of the R Session. It is guaranteed by the operating system that two R sessions running simultaneously will have different IDs, but it is possible that R sessions running at different times will have the same ID.

Usage

Sys.getpid()

Value

An integer, usually a small integer between 0 and 32767 under Unix-alikes and a much small integer under Windows.

Examples

Sys.getpid()


Translate Text Messages

Description

If Native Language Support was enabled in this build of R, attempt to translate character vectors or set where the translations are to be found.

Usage

gettext(..., domain = NULL)

ngettext(n, msg1, msg2, domain = NULL)

bindtextdomain(domain, dirname = NULL)

Arguments

... | One or more character vectors.
domain | The ‘domain’ for the translation.
n | a non-negative integer.
msg1 | the message to be used in English for n = 1.
msg2 | the message to be used in English for n = 0, 2, 3,....
dirname | The directory in which to find translated message catalogs for the domain.

Details

If domain is NULL or "", a domain is searched for based on the namespace which contains the function calling gettext or ngettext. If a suitable domain can be found, each character string is offered for translation, and replaced by its translation into the current language if one is found.

Conventionally the domain for R warning/error messages in package pkg is "R-pkg", and that for C-level messages is "pkg".

For gettext, leading and trailing whitespace is ignored when looking for the translation.

ngettext is used where the message needs to vary by a single integer. Translating such messages is subject to very specific rules for different languages: see the GNU Gettext Manual. The string will often contain a single instance of %d to be used in sprintf. If English is used, msg1 is returned if n == 1 and msg2 in all other cases.

Value

For gettext, a character vector, one element per string in .... If translation is not enabled or no domain is found or no translation is found in that domain, the original strings are returned.
For ngettext, a character string.
For bindtextdomain, a character string giving the current base directory, or NULL if setting it failed.

See Also

stop and warning make use of gettext to translate messages.

xgettext for extracting translatable strings from R source files.

Examples

bindtextdomain("R")  # non-null iff NLS is enabled

for(n in 0:3)
    print(sprintf(ngettext(n, "%d variable has missing values",
                              "%d variables have missing values"),
                  n))

## Not run:
## for translation, those strings should appear in R-pkg.pot as
msgid        "%d variable has missing values"
msgid_plural "%d variables have missing values"
msgstr[0] ""
msgstr[1] ""
## End(Not run)

miss <- c("one", "or", "another")
cat(ngettext(length(miss), "variable", "variables"),
    paste(sQuote(miss), collapse=", "),
    ngettext(length(miss), "contains", "contain"), "missing values\n")

## better for translators would be to use
cat(sprintf(ngettext(length(miss),
                     "variable %s contains missing values\n",
                     "variables %s contain missing values\n"),
            paste(sQuote(miss), collapse=", ")))


Get or Set Working Directory

Description

getwd returns an absolute filename representing the current working directory of the R process; setwd(dir) is used to set the working directory to dir.

Usage

getwd()
setwd(dir)

Arguments

dir A character string.

Value

getwd returns a character vector, or NULL if the working directory is not available. On Windows the path returned will use / as the path separator.
setwd returns the currrent directory before the change, invisibly. It will give an error if it does not succeed.

Note

These functions are not implemented on all platforms.

See Also

list.files for the contents of a directory.

Examples

(WD <- getwd())
if (!is.null(WD)) setwd(WD)


Generate Factor Levels

Description

Generate factors by specifying the pattern of their levels.

Usage

gl(n, k, length = n*k, labels = 1:n, ordered = FALSE)

Arguments

n | an integer giving the number of levels.
k | an integer giving the number of replications.
length | an integer giving the length of the result.
labels | an optional vector of labels for the resulting factor levels.
ordered | a logical indicating whether the result should be ordered or not.

Value

The result has levels from 1 to n with each value replicated in groups of length k out to a total length of length.
gl is modelled on the GLIM function of the same name.

See Also

The underlying factor().

Examples

## First control, then treatment:
gl(2, 8, label = c("Control", "Treat"))
## 20 alternating 1s and 2s
gl(2, 1, 20)
## alternating pairs of 1s and 2s
gl(2, 2, 20)


Pattern Matching and Replacement

Description

grep searches for matches to pattern (its first argument) within the character vector x (second argument). regexpr and gregexpr do too, but return more detail in a different format.

sub and gsub perform replacement of matches determined by regular expression matching.

Usage

grep(pattern, x, ignore.case = FALSE, extended = TRUE,
     perl = FALSE, value = FALSE, fixed = FALSE, useBytes = FALSE)

sub(pattern, replacement, x,
    ignore.case = FALSE, extended = TRUE, perl = FALSE,
    fixed = FALSE, useBytes = FALSE)

gsub(pattern, replacement, x,
     ignore.case = FALSE, extended = TRUE, perl = FALSE,
     fixed = FALSE, useBytes = FALSE)

regexpr(pattern, text, extended = TRUE, perl = FALSE,
        fixed = FALSE, useBytes = FALSE)

gregexpr(pattern, text, extended = TRUE, perl = FALSE,
         fixed = FALSE, useBytes = FALSE)

Arguments

pattern | character string containing a regular expression (or character string for fixed = TRUE) to be matched in the given character vector. Coerced by as.character to a character string if possible.
x, text | a character vector where matches are sought, or an object which can be coerced by as.character to a character vector.
ignore.case | if FALSE, the pattern matching is case sensitive and if TRUE, case is ignored during matching.
extended | if TRUE, extended regular expression matching is used, and if FALSE basic regular expressions are used.
perl | logical. Should perl-compatible regexps be used? Has priority over extended.
value | if FALSE, a vector containing the (integer) indices of the matches determined by grep is returned, and if TRUE, a vector containing the matching elements themselves is returned.
fixed | logical. If TRUE, pattern is a string to be matched as is. Overrides all conflicting arguments.
useBytes | logical. If TRUE the matching is done byte-by-byte rather than character-by-character. See Details.
replacement | a replacement for matched pattern in sub and gsub. Coerced to character if possible. For fixed = FALSE this can include backreferences "\1" to "\9" to parenthesized subexpressions of pattern. For perl = TRUE only, it can also contain "\U" or "\L" to convert the rest of the replacement to upper or lower case.

Details

Arguments which should be character strings or character vectors are coerced to character if possible.

The two *sub functions differ only in that sub replaces only the first occurrence of a pattern whereas gsub replaces all occurrences.

For regexpr it is an error for pattern to be NA, otherwise NA is permitted and matches only itself.

The regular expressions used are those specified by POSIX 1003.2, either extended or basic, depending on the value of the extended argument, unless perl = TRUE when they are those of PCRE, http://www.pcre.org/. (The exact set of patterns supported may depend on the version of PCRE installed on the system in use, if R was configured to use the system PCRE. R's internal copy used PCRE 6.7.)

useBytes is only used if fixed = TRUE or perl = TRUE. For grep its main effect is to avoid errors/warnings about invalid inputs, but for regexpr it changes the interpretation of the output.

Value

For grep a vector giving either the indices of the elements of x that yielded a match or, if value is TRUE, the matched elements of x (after coercion, preserving names but no other attributes).
For sub and gsub a character vector of the same length and with the same attributes as x (after possible coercion).
For regexpr an integer vector of the same length as text giving the starting position of the first match, or -1 if there is none, with attribute "match.length" giving the length of the matched text (or -1 for no match). In a multi-byte locale these quantities are in characters rather than bytes unless useBytes = TRUE is used with fixed = TRUE or perl = TRUE.
For gregexpr a list of the same length as text each element of which is an integer vector as in regexpr, except that the starting positions of every match are given.
If in a multi-byte locale the pattern or replacement is not a valid sequence of bytes, an error is thrown. An invalid string in x or text is a non-match with a warning for grep or regexpr, but an error for sub or gsub.

Warning

The standard regular-expression code has been reported to be very slow when applied to extremely long character strings (tens of thousands of characters or more): the code used when perl = TRUE seems much faster and more reliable for such usages.

The standard version of gsub does not substitute correctly repeated word-boundaries (e.g. pattern = "\b"). Use perl = TRUE for such matches.

The perl = TRUE option is only implemented for single-byte and UTF-8 encodings, and will warn if used in a non-UTF-8 multi-byte locale (unless useBytes = TRUE).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole (grep)

See Also

regular expression (aka regexp) for the details of the pattern specification.

glob2rx to turn wildcard matches into regular expressions.

agrep for approximate matching.

tolower, toupper and chartr for character translations. charmatch, pmatch, match. apropos uses regexps and has nice examples.

Examples

grep("[a-z]", letters)

txt <- c("arm","foot","lefroo", "bafoobar")
if(any(i <- grep("foo",txt)))
   cat("'foo' appears at least once in\n\t",txt,"\n")
i # 2 and 4
txt[i]

## Double all 'a' or 'b's;  "\" must be escaped, i.e., 'doubled'
gsub("([ab])", "\\1_\\1_", "abc and ABC")

txt <- c("The", "licenses", "for", "most", "software", "are",
  "designed", "to", "take", "away", "your", "freedom",
  "to", "share", "and", "change", "it.",
   "", "By", "contrast,", "the", "GNU", "General", "Public", "License",
   "is", "intended", "to", "guarantee", "your", "freedom", "to",
   "share", "and", "change", "free", "software", "--",
   "to", "make", "sure", "the", "software", "is",
   "free", "for", "all", "its", "users")
( i <- grep("[gu]", txt) ) # indices
stopifnot( txt[i] == grep("[gu]", txt, value = TRUE) )

## Note that in locales such as en_US this includes B as the
## collation order is aAbBcCdEe ...
(ot <- sub("[b-e]",".", txt))
txt[ot != gsub("[b-e]",".", txt)]#- gsub does "global" substitution

txt[gsub("g","#", txt) !=
    gsub("g","#", txt, ignore.case = TRUE)] # the "G" words

regexpr("en", txt)

gregexpr("e", txt)

## trim trailing white space
str = 'Now is the time      '
sub(' +$', '', str)  ## spaces only
sub('[[:space:]]+$', '', str) ## white space, POSIX-style
sub('\\s+$', '', str, perl = TRUE) ## Perl-style white space

## capitalizing
gsub("(\\w)(\\w*)", "\\U\\1\\L\\2", "a test of capitalizing", perl=TRUE)
gsub("\\b(\\w)", "\\U\\1", "a test of capitalizing", perl=TRUE)


S3 Group Generic Functions

Description

Group generic methods can be defined for four pre-specified groups of functions, Math, Ops, Summary and Complex. (There are no objects of these names in base R, but there are in the methods package.)

A method defined for an individual member of the group takes precedence over a method defined for the group as a whole.

Usage

## S3 methods for group generics have prototypes:
Math(x, ...)
Ops(e1, e2)
Complex(z)
Summary(..., na.rm = FALSE)

Arguments

x, z, e1, e2 | objects.
... | further arguments passed to methods.
na.rm | logical: should missing values be removed?

Details

There are four groups for which S3 methods can be written, namely the "Math", "Ops", "Summary" and "Complex" groups. These are not R objects, but methods can be supplied for them and base R contains factor, data.frame and difftime methods for the first three groups. (There is also a ordered method for Ops, POSIXt and Date methods for Math and Ops, package_version methods for Ops and Summary, as well as a ts method for Ops in package stats.)

  1. Group "Math":
    • abs, sign, sqrt,
      floor, ceiling, trunc,
      round, signif
    • exp, log,
      cos, sin, tan,
      acos, asin, atan

      cosh, sinh, tanh,
      acosh, asinh, atanh

    • lgamma, gamma, gammaCody,
      digamma, trigamma
    • cumsum, cumprod, cummax, cummin

    Members of this group dispatch on x.

  2. Group "Ops":
    • "+", "-", "*", "/", "^", "%%", "%/%"
    • "&", "|", "!"
    • "==", "!=", "<", "<=", ">=", ">"

    This group contains both binary and unary operators (+, - and !): when a unary operator is encountered the Ops method is called with one argument and e2 is missing.

    The classes of both arguments are considered in dispatching any member of this group. For each argument its vector of classes is examined to see if there is a matching specific (preferred) or Ops method. If a method is found for just one argument or the same method is found for both, it is used. If different methods are found, there is a warning about ‘incompatible methods’: in that case or if no method is found for either argument the internal method is used.

  3. Group "Summary":
    • all, any
    • sum, prod
    • min, max
    • range

    Members of this group dispatch on the first argument supplied.

  4. Group "Complex":
    • Arg, Conj, Im, Mod, Re

    Members of this group dispatch on z.

Note that a method will used for either one of these groups or one of its members only if it corresponds to a "class" attribute, as the internal code dispatches on oldClass and not on class. This is for efficiency: having to dispatch on, say, Ops.integer would be too slow.

The number of arguments supplied for "Math" group generic methods is not checked prior to dispatch. (Most have default methods expecting one argument, but log, round and signif expect two.)

Technical Details

The details of method dispatch and variables such as .Generic are discussed in the help for UseMethod. There are a few small differences:

  • For the operators of group Ops, the object .Method is a length-two character vector with elements the methods selected for the left and right arguments respectively. (If no method was selected, the corresponding element is "".)
  • Object .Group records the group used for dispatch (if a specific method is used this is "").

References

Appendix A, Classes and Methods of
Chambers, J. M. and Hastie, T. J. eds (1992) Statistical Models in S. Wadsworth & Brooks/Cole.

See Also

methods for methods of non-Internal generic functions.

S4groupGeneric for group generics for S4 methods.

Examples

d.fr <- data.frame(x=1:9, y=rnorm(9))
class(1 + d.fr) == "data.frame" ##-- add to d.f. ...

methods("Math")
methods("Ops")
methods("Summary")
methods("Complex")  # none in base R


(De)compress I/O Through Connections

Description

gzcon provides a modified connection that wraps an existing connection, and decompresses reads or compresses writes through that connection. Standard gzip headers are assumed.

Usage

gzcon(con, level = 6, allowNonCompressed = TRUE)

Arguments

con | a connection.
level | integer between 0 and 9, the compression level when writing.
allowNonCompressed | logical. When reading, should non-compressed input be allowed?

Details

If con is open then the modified connection is opened. Closing the wrapper connection will also close the underlying connection.

Reading from a connection which does not supply a gzip magic header is equivalent to reading from the original connection if allowNonCompressed is true, otherwise an error.

The original connection becomes unusable: any object pointing to it will now refer to the modified connection.

When the connection is opened for reading, the input is expected to start with the gzip magic header. If it does not and if allowNonCompressed = TRUE (the default) the input is read as-is.

Value

An object inheriting from class "connection". This is the same connection number as supplied, but with a modified internal structure.

See Also

gzfile

Examples

## Not run:
## This example is no longer available
## print the value to see what objects were created.
con <- url("http://hesweb1.med.virginia.edu/biostat/s/data/sav/kprats.sav")
print(load(con))
close(con)
## End(Not run)

## gzfile and gzcon can inter-work.
## Of course here one would used gzfile, but file() can be replaced by
## any other connection generator.
zz <- gzfile("ex.gz", "w")
cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
close(zz)
readLines(zz <- gzcon(file("ex.gz", "rb")))
close(zz)
unlink("ex.gz")

zz <- gzcon(file("ex.gz", "wb"))
cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
close(zz)
readLines(zz <- gzfile("ex.gz"))
close(zz)
unlink("ex.gz")


Display Numbers in Hexadecimal

Description

Convert or print integers in hexadecimal format, with as many digits as are needed to display the largest, using leading zeroes as necessary.

Usage

## S3 method for class 'hexmode':
as.character(x, ...)

## S3 method for class 'hexmode':
format(x, ...)

## S3 method for class 'hexmode':
print(x, ...)

Arguments

x | An object inheriting from class "hexmode".
... | further arguments passed to or from other methods.

Details

Class "hexmode" consists of integer vectors with that class attribute, used merely to ensure that they are printed in hex.

See Also

octmode


Hyperbolic Functions

Description

These functions give the obvious hyperbolic functions. They respectively compute the hyperbolic cosine, sine, tangent, and their inverses, arc-cosine, arc-sine, arc-tangent (or “area cosine”, etc).

Usage

cosh(x)
sinh(x)
tanh(x)
acosh(x)
asinh(x)
atanh(x)

Arguments

x a numeric or complex vector

Details

These are generic functions: methods can be defined for them individually or via the Math group generic.

Branch cuts are consistent with the inverse trigonometric functions asin() et seq, and agree with those defined in Abramowitz and Stegun, figure 4.7, page 86.

References

Abramowitz, M. and Stegun, I. A. (1972) Handbook of Mathematical Functions. New York: Dover.
Chapter 4. Elementary Transcendental Functions: Logarithmic, Exponential, Circular and Hyperbolic Functions

See Also

The trigonometric functions, cos, sin, tan, and their inverses acos, asin, atan.

The logistic distribution function plogis is a shifted version of tanh() for numeric x.


Convert Character Vector between Encodings

Description

This uses system facilities to convert a character vector between encodings: the ‘i’ stands for ‘internationalization’.

Usage

iconv(x, from, to, sub=NA)

iconvlist()

Arguments

x | A character vector, or an object to be converted to a character vector by as.character.
from | A character string describing the current encoding.
to | A character string describing the target encoding.
sub | character string. If not NA it is used to replace any non-convertible bytes in the input. (This would normally be a single character, but can be more. If "byte", the indication is "<xx>" with the hex code of the byte.

Details

The names of encodings and which ones are available (and indeed, if any are) is platform-dependent. On systems that support R's iconv you can use "" for the encoding of the current locale, as well as "latin1" and "UTF-8".

iconvlist provides an alphabetical list of the supported encodings.

Elements of x which cannot be converted (perhaps because they are invalid or because they cannot be represented in the target encoding) will be returned as NA unless sub is specified.

Some versions of iconv will allow transliteration by appending //TRANSLIT to the to encoding: see the examples.

Value

A character vector of the same length and the same attributes as x (after conversion).

Note

Not all platforms support these functions. See also capabilities("iconv").

See Also

localeToCharset, file.

Examples

## Not run:
iconvlist()

## convert from Latin-2 to UTF-8: two of the glibc iconv variants.
iconv(x, "ISO_8859-2", "UTF-8")
iconv(x, "LATIN2", "UTF-8")

## Both x below are in latin1 and will only display correctly in a
## latin1 locale.
(x <- "fa\xE7ile")
charToRaw(xx <- iconv(x, "latin1", "UTF-8"))
## in a UTF-8 locale, print(xx)

iconv(x, "latin1", "ASCII")          #   NA
iconv(x, "latin1", "ASCII", "?")     # "fa?ile"
iconv(x, "latin1", "ASCII", "")      # "faile"
iconv(x, "latin1", "ASCII", "byte")  # "fa<e7>ile"

# Extracts from R help files
(x <- c("Ekstr\xf8m", "J\xf6reskog", "bi\xdfchen Z\xfcrcher"))
iconv(x, "latin1", "ASCII//TRANSLIT")
iconv(x, "latin1", "ASCII", sub="byte")
## End(Not run)


Test Objects for Exact Equality

Description

The safe and reliable way to test two objects for being exactly equal. It returns TRUE in this case, FALSE in every other case.

Usage

identical(x, y)

Arguments

x, y any R objects.

Details

A call to identical is the way to test exact equality in if and while statements, as well as in logical expressions that use && or ||. In all these applications you need to be assured of getting a single logical value.

Users often use the comparison operators, such as == or !=, in these situations. It looks natural, but it is not what these operators are designed to do in R. They return an object like the arguments. If you expected x and y to be of length 1, but it happened that one of them wasn't, you will not get a single FALSE. Similarly, if one of the arguments is NA, the result is also NA. In either case, the expression if(x == y).... won't work as expected.

The function all.equal is also sometimes used to test equality this way, but was intended for something different: It allows for “reasonable” differences in numeric results.

The computations in identical are also reliable and usually fast. There should never be an error. The only known way to kill identical is by having an invalid pointer at the C level, generating a memory fault. It will usually find inequality quickly. Checking equality for two large, complicated objects can take longer if the objects are identical or nearly so, but represent completely independent copies. For most applications, however, the computational cost should be negligible.

identical sees NaN as different from as.double(NA), but all NaNs are equal (and all NA of the same type are equal).

Comparison of character strings allows for embedded nul characters. Comparison of attributes view them as a set (and not a vector, so order is not tested).

Value

A single logical value, TRUE or FALSE, never NA and never anything other than a single value.

Author(s)

John Chambers

References

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language. Springer.

See Also

all.equal for descriptions of how two objects differ; Comparison for operators that generate elementwise comparisons. isTRUE is a simple wrapper based on identical.

Examples

identical(1, NULL) ## FALSE -- don't try this with ==
identical(1, 1.)   ## TRUE in R (both are stored as doubles)
identical(1, as.integer(1)) ## FALSE, stored as different types

x <- 1.0; y <- 0.99999999999
## how to test for object equality allowing for numeric fuzz :
(E <- all.equal(x,y))
isTRUE(E) # which is simply defined to just use
identical(TRUE, E)
## If all.equal thinks the objects are different, it returns a
## character string, and the above expression evaluates to FALSE

# even for unusual R objects :
identical(.GlobalEnv, environment())


Conditional Element Selection

Description

ifelse returns a value with the same shape as test which is filled with elements selected from either yes or no depending on whether the element of test is TRUE or FALSE.

Usage

ifelse(test, yes, no)

Arguments

test | an object which can be coerced to logical mode.
yes | return values for true elements of test.
no | return values for false elements of test.

Details

If yes or no are too short, their elements are recycled. yes will be evaluated if and only if any element of test is true, and analogously for no.

Missing values in test give missing values in the result.

Value

A vector of the same length and attributes (including class) as test and data values from the values of yes or no. The mode of the answer will be coerced from logical to accommodate first any values taken from yes and then any values taken from no.

Warning

The mode of the result may depend on the value of test, and the class attribute of the result is taken from test and may be inappropriate for the values selected from yes and no.

Sometimes it is better to use a construction such as (tmp <- yes; tmp[!test] <- no[!test]; tmp), possibly extended to handle missing values in test.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

if.

Examples

x <- c(6:-4)
sqrt(x)#- gives warning
sqrt(ifelse(x >= 0, x, NA))# no warning

## Note: the following also gives the warning !
ifelse(x >= 0, sqrt(x), NA)

## example of different return modes:
yes <- 1:3
no <- pi^(0:3)
typeof(ifelse(NA, yes, no))   # logical
typeof(ifelse(TRUE, yes, no)) # integer
typeof(ifelse(FALSE, yes, no))# double


Integer Vectors

Description

Creates or tests for objects of type "integer".

Usage

integer(length = 0)
as.integer(x, ...)
is.integer(x)

Arguments

length | desired length.
x | object to be coerced or tested.
... | further arguments passed to or from other methods.

Details

Integer vectors exist so that data can be passed to C or Fortran code which expects them, and so that small integer data can be represented exactly and compactly.

Note that on almost all implementations of R the range of representable integers is restricted to about +/-2*10^9: doubles can hold much larger integers exactly.

Value

integer creates a integer vector of the specified length. Each element of the vector is equal to 0.
as.integer attempts to coerce its argument to be of integer type. The answer will be NA unless the coercion succeeds. Real values larger in modulus than the largest integer are coerced to NA (unlike S which gives the most extreme integer of the same sign). Non-integral numeric values are truncated towards zero (i.e., as.integer(x) equals trunc(x) there), and imaginary parts of complex numbers are discarded (with a warning). Character strings containing either a decimal representation or a heaxadecimal representation (starting with 0x or 0X) can be converted, as well as any allowed by the platform for real numbers. Like as.vector it strips attributes including names.
is.integer returns TRUE or FALSE depending on whether its argument is of integer type or not. is.integer is generic: you can write methods to handle specific classes of objects, see InternalMethods. There is a method for factors which returns FALSE.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

round (and ceiling and floor on that help page) to convert to integral values.

Examples

  ## as.integer() truncates:
  x <- pi * c(-1:1,10)
  as.integer(x)


Compute Factor Interactions

Description

interaction computes a factor which represents the interaction of the given factors. The result of interaction is always unordered.

Usage

interaction(..., drop = FALSE, sep = ".")

Arguments

... | the factors for which interaction is to be computed, or a single list giving those factors.
drop | if drop is TRUE, unused factor levels are dropped from the result. The default is to retain all factor levels.
sep | string to construct the new level labels by joining the constituent ones.

Value

A factor which represents the interaction of the given factors. The levels are labelled as the levels of the individual factors joined by sep, by . by default.
The levels are ordered so the level of the first factor varies fastest, then the second and so on. This is the reverse of lexicographic ordering, and differs from :. (It is done this way for compatibility with S.)

References

Chambers, J. M. and Hastie, T. J. (1992) Statistical Models in S. Wadsworth & Brooks/Cole.

See Also

factor; : where f:g is similar to interaction(f, g, sep=":") when f and g are factors.

Examples

a <- gl(2, 4, 8)
b <- gl(2, 2, 8, label = c("ctrl", "treat"))
s <- gl(2, 1, 8, label = c("M", "F"))
interaction(a, b)
interaction(a, b, s, sep = ":")


Is R Running Interactively?

Description

Return TRUE when R is being used interactively and FALSE otherwise.

Usage

interactive()

See Also

source, .First

Examples

 .First <- function() if(interactive()) x11()


Call an Internal Function

Description

.Internal performs a call to an internal code which is built in to the R interpreter.

Only true R wizards should even consider using this function, and only R developers can add to the list of internal functions.

Usage

 .Internal(call)

Arguments

call a call expression

See Also

.Primitive, .External (the nearest equivalent available to users).


Change the Print Mode to Invisible

Description

Return a (temporarily) invisible copy of an object.

Usage

invisible(x)

Arguments

x an arbitrary R object.

Details

This function can be useful when it is desired to have functions return values which can be assigned, but which do not print when they are not assigned.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

return, function.

Examples

# These functions both return their argument
f1 <- function(x) x
f2 <- function(x) invisible(x)
f1(1)# prints
f2(1)# does not


Finite, Infinite and NaN Numbers

is.finite(base) R Documentation

Finite Infinite and NaN Numbers

Description

is.finite and is.infinite return a vector of the same length as x, indicating which elements are finite (not infinite and not missing).

Inf and -Inf are positive and negative “infinity” whereas NaN means “Not a Number”. (These apply to numeric values and real and imaginary parts of complex values but not to values of integer vectors.)

Usage

is.finite(x)
is.infinite(x)
Inf
NaN
is.nan(x)

Arguments

x (numerical) object to be tested.

Details

is.finite returns a vector of the same length as x the jth element of which is TRUE if x[j] is finite (i.e., it is not one of the values NA, NaN, Inf or -Inf). All elements of types other than logical, integer, numeric and complex vectors are false. Complex numbers are finite if both the real and imaginary parts are.

is.infinite returns a vector of the same length as x the jth element of which is TRUE if x[j] is infinite (i.e., equal to one of Inf or -Inf). This will be false unless x is numeric or complex. Complex numbers are infinite if either the real and imaginary part is.

is.nan tests if a numeric value is NaN. Do not test equality to NaN, or even use identical, since systems typically have many different NaN values. One of these is used for the numeric missing value NA, and is.nan is false for that value. It is generic: you can write methods to handle specific classes of objects, see InternalMethods. The default method handles real and complex vectors: a complex number is regarded as NaN if either the real or imaginary part is NaN but not NA.

Note

In R, basically all mathematical functions (including basic Arithmetic), are supposed to work properly with +/- Inf and NaN as input or output.

The basic rule should be that calls and relations with Infs really are statements with a proper mathematical limit.

References

The IEC 60559 standard, also know as the ANSI/IEEE 754 Floating-Point Standard.

D. Goldberg (1991) What Every Computer Scientist Should Know about Floating-Point Arithmetic ACM Computing Surveys, 23(1).
Postscript version available at http://www.validlab.com/goldberg/paper.ps Extended PDF version at http://www.validlab.com/goldberg/paper.pdf

http://grouper.ieee.org/groups/754/ for accessible information.

The C99 function isfinite is used for is.finite if available.

See Also

NA, ‘Not Available’ which is not a number as well, however usually used for missing values and applies to many modes, not just numeric.

Examples

pi / 0 ## = Inf a non-zero number divided by zero creates infinity
0 / 0  ## =  NaN

1/0 + 1/0# Inf
1/0 - 1/0# NaN

stopifnot(
    1/0 == Inf,
    1/Inf == 0
)
sin(Inf)
cos(Inf)
tan(Inf)


Is an Object of Type (Primitive) Function?

Description

Checks whether its argument is a (primitive) function.

Usage

is.function(x)
is.primitive(x)

Arguments

x an R object.

Details

is.function is generic: you can write methods to handle specific classes of objects, see InternalMethods.

is.primitive(x) tests if x is a primitive function (either a "builtin" or "special" as from typeof)?

Value

TRUE if x is a (primitive) function, and FALSE otherwise.

Examples

is.function(1) # FALSE
is.function(is.primitive)  # TRUE: it is a function, but ..
is.primitive(is.primitive) # FALSE:it's not a primitive one, whereas
is.primitive(is.function)  # TRUE: that one *is*


Is an Object a Language Object?

Description

is.language returns TRUE if x is a variable name, a call, or an expression.

Usage

is.language(x)

Arguments

x object to be tested.

Details

is.language is generic: you can write methods to handle specific classes of objects, see InternalMethods.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Examples

ll <- list(a = expression(x^2 - 2*x + 1), b = as.name("Jim"),
           c = as.expression(exp(1)), d = call("sin", pi))
sapply(ll, typeof)
sapply(ll, mode)
stopifnot(sapply(ll, is.language))


Is an Object “internally classed”?

Description

A function rather for internal use. It returns TRUE if the object x has the R internal OBJECT attribute set, and FALSE otherwise.

Usage

is.object(x)

Arguments

x object to be tested.

Details

is.object is generic: you can write methods to handle specific classes of objects, see InternalMethods.

See Also

class, and methods.

Examples

is.object(1) # FALSE
is.object(as.factor(1:3)) # TRUE


Is an Object Atomic or Recursive?

Description

is.atomic returns TRUE if x is an atomic vector (or NULL) and FALSE otherwise.

is.recursive returns TRUE if x has a recursive (list-like) structure and FALSE otherwise.

Usage

is.atomic(x)
is.recursive(x)

Arguments

x object to be tested.

Details

These are generic: you can write methods to handle specific classes of objects, see InternalMethods. The description here applies only to the default method.

is.atomic is true for the atomic vector types ("logical", "integer", "numeric", "complex", "character" and "raw") and NULL.

Most types of language objects are regarded as recursive: those which are not are the atomic vector types, NULL and symbols (as given by as.name).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

is.list, is.language, etc, and the demo("is.things").

Examples

is.a.r <- function(x) c(is.atomic(x), is.recursive(x))

is.a.r(c(a=1,b=3))      # TRUE FALSE
is.a.r(list())          # FALSE TRUE ??
is.a.r(list(2))         # FALSE TRUE
is.a.r(lm)              # FALSE TRUE
is.a.r(y ~ x)           # FALSE TRUE
is.a.r(expression(x+1)) # FALSE TRUE (not in 0.62.3!)


Is an Object of Single Precision Type?

Description

is.single reports an error. There are no single precision values in R.

Usage

is.single(x)

Arguments

x object to be tested.

Details

is.single is generic: you can write methods to handle specific classes of objects, see InternalMethods.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.


Are we using R, rather than S?

is.R(base) R Documentation

Are we using R rather than S?

Description

Test if running under R.

Usage

is.R()

Details

The function has been written such as to correctly run in all versions of R, S and S-PLUS. In order for code to be runnable in both R and S dialects previous to S-PLUS 8.0, your code must either define is.R or use it as

if (exists("is.R") && is.function(is.R) && is.R()) {
## R-specific code
} else {
## S-version of code
}

Value

is.R returns TRUE if we are using R and FALSE otherwise.

See Also

R.version, system.

Examples

x <- runif(20); small <- x < 0.4
## In the early years of R, 'which()' only existed in R:
if(is.R()) which(small) else seq(along=small)[small]


Test for an S4 object

Description

Tests whether the object was created from a formally defined class.

Usage

isS4(object)

asS4(object, value = TRUE)

Arguments

object | Any R object.
value | A single logical value; not NA.

Details

Note that this function does not rely on the methods package, so in particular it can be used to detect the need to require() that package.

You should not set the flag directly unless you really know why. In the future, S4 methods may be restricted S4 objects, for primitive functions; then asS4 would allow method dispatch of S4 methods for S3 classes. For all other purposes, an object will satisfy isS4(x) if and only if it should.

Value

isS4 always returns TRUE or FALSE according to whether the internal flag marking an S4 object has been turned on for this object.
asS4 will turn this flag on or off. But see the details.

Examples

isS4(pi) # FALSE
isS4(getClass("MethodDefinition")) # TRUE


Test if a Matrix or other Object is Symmetric

Description

Generic function to test if object is symmetric or not. Currently only a matrix method is implemented.

Usage

isSymmetric(object, ...)
## S3 method for class 'matrix':
isSymmetric(object, tol = 100 * .Machine$double.eps, ...)

Arguments

object | any R object; a matrix for the matrix method.
tol | numeric scalar >= 0. Smaller differences are not considered, see all.equal.numeric.
... | further arguments passed to methods; the matrix method passes these to all.equal.

Details

The matrix method is used inside eigen by default to test symmetry of matrices ``up to rounding error'', using all.equal. It might not be appropriate in all situations.

Value

logical indicating if object is symmetric or not.

See Also

eigen which calls isSymmetric when its symmetric argument is missing, as per default.

Examples

isSymmetric(D3 <- diag(3)) # -> TRUE

D3[2,1] <- 1e-100
D3
isSymmetric(D3) # TRUE
isSymmetric(D3, tol = 0) # FALSE for zero-tolerance


Add 'Jitter' (Noise) to Numbers

Description

Add a small amount of noise to a numeric vector.

Usage

jitter(x, factor=1, amount = NULL)

Arguments

x | numeric vector to which jitter should be added.
factor | numeric
amount | numeric; if positive, used as amount (see below), otherwise, if = 0 the default is factor * z/50. Default (NULL): factor * d/5 where d is about the smallest difference between x values.

Details

The result, say r, is r <- x + runif(n, -a, a) where n <- length(x) and a is the amount argument (if specified).

Let z <- max(x) - min(x) (assuming the usual case). The amount a to be added is either provided as positive argument amount or otherwise computed from z, as follows:

If amount == 0, we set a <- factor * z/50 (same as S).

If amount is NULL (default), we set a <- factor * d/5 where d is the smallest difference between adjacent unique (apart from fuzz) x values.

Value

jitter(x,...) returns a numeric of the same length as x, but with an amount of noise added in order to break ties.

Author(s)

Werner Stahel and Martin Maechler, ETH Zurich

References

Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P.A. (1983) Graphical Methods for Data Analysis. Wadsworth; figures 2.8, 4.22, 5.4.

Chambers, J. M. and Hastie, T. J. (1992) Statistical Models in S. Wadsworth & Brooks/Cole.

See Also

rug which you may want to combine with jitter.

Examples

round(jitter(c(rep(1,3),  rep(1.2, 4), rep(3,3))), 3)
## These two 'fail' with S-plus 3.x:
jitter(rep(0, 7))
jitter(rep(10000,5))


Estimate the Condition Number

Description

An estimate of the condition number of a matrix or of the R matrix of a QR decomposition, perhaps of a linear fit. The condition number is defined as the ratio of the largest to the smallest non-zero singular value of the matrix.

Usage

kappa(z, ...)
## S3 method for class 'lm':
kappa(z, ...)
## Default S3 method:
kappa(z, exact = FALSE, ...)
## S3 method for class 'qr':
kappa(z, ...)

kappa.tri(z, exact = FALSE, ...)

Arguments

z | A matrix or a the result of qr or a fit from a class inheriting from "lm".
exact | logical. Should the result be exact?
... | further arguments passed to or from other methods.

Details

If exact = FALSE (the default) the condition number is estimated by a cheap approximation. Following S, this uses the LINPACK routine ‘dtrco.f’. However, in R (or S) the exact calculation is also likely to be quick enough.

kappa.tri is an internal function called by kappa.qr.

Value

The condition number, kappa, or an approximation if exact = FALSE.

Author(s)

The design was inspired by (but differs considerably from) the S function of the same name described in Chambers (1992).

References

Chambers, J. M. (1992) Linear models. Chapter 4 of Statistical Models in S eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole.

See Also

svd for the singular value decomposition and qr for the QR one.

Examples

kappa(x1 <- cbind(1,1:10))# 15.71
kappa(x1, exact = TRUE)        # 13.68
kappa(x2 <- cbind(x1,2:11))# high! [x2 is singular!]

hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
sv9 <- svd(h9 <- hilbert(9))$ d
kappa(h9)# pretty high!
kappa(h9, exact = TRUE) == max(sv9) / min(sv9)
kappa(h9, exact = TRUE) / kappa(h9) # .677 (i.e., rel.error = 32%)


Kronecker products on arrays

Description

Computes the generalised kronecker product of two arrays, X and Y. kronecker(X, Y) returns an array A with dimensions dim(X) * dim(Y).

Usage

kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...)
X %x% Y

Arguments

X | A vector or array.
Y | A vector or array.
FUN | a function; it may be a quoted string.
make.dimnames | Provide dimnames that are the product of the dimnames of X and Y.
... | optional arguments to be passed to FUN.

Details

If X and Y do not have the same number of dimensions, the smaller array is padded with dimensions of size one. The returned array comprises submatrices constructed by taking X one term at a time and expanding that term as FUN(x, Y, ...).

%x% is an alias for kronecker (where FUN is hardwired to "*").

Author(s)

Jonathan Rougier, J.C.Rougier@durham.ac.uk

References

Shayle R. Searle (1982) Matrix Algebra Useful for Statistics. John Wiley and Sons.

See Also

outer, on which kronecker is built and %*% for usual matrix multiplication.

Examples

# simple scalar multiplication
( M <- matrix(1:6, ncol=2) )
kronecker(4, M)
# Block diagonal matrix:
kronecker(diag(1, 3), M)

# ask for dimnames

fred <- matrix(1:12, 3, 4, dimnames=list(LETTERS[1:3], LETTERS[4:7]))
bill <- c("happy" = 100, "sad" = 1000)
kronecker(fred, bill, make.dimnames = TRUE)

bill <- outer(bill, c("cat"=3, "dog"=4))
kronecker(fred, bill, make.dimnames = TRUE)


Localization Information

Description

Report on localization information.

Usage

l10n_info()

Value

A list with two logical components:

MBCS | If a multi-byte character set in use?
UTF-8 | Is this a UTF-8 locale?

See Also

Sys.getlocale, localeconv

Examples

l10n_info()


Find Labels from Object

Description

Find a suitable set of labels from an object for use in printing or plotting, for example. A generic function.

Usage

labels(object, ...)

Arguments

object | Any R object: the function is generic.
... | further arguments passed to or from other methods.

Value

A character vector or list of such vectors. For a vector the results is the names or seq(along=x) and for a data frame or array it is the dimnames (with NULL expanded to seq(len=d[i]).

References

Chambers, J. M. and Hastie, T. J. (1992) Statistical Models in S. Wadsworth & Brooks/Cole.


Apply a Function over a List or Vector

Description

lapply returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X.

sapply is a “user-friendly” version of lapply by default returning a vector or matrix if appropriate.

replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).

Usage

lapply(X, FUN, ...)

sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)

replicate(n, expr, simplify = TRUE)

Arguments

X | a vector (atomic or list) or an expressions vector. Other objects (including classed objects) will be coerced by as.list.
FUN | the function to be applied to each element of X: see Details. In the case of functions like +, %*%, etc., the function name must be backquoted or quoted.
... | optional arguments to FUN.
simplify | logical; should the result be simplified to a vector or matrix if possible?
USE.NAMES | logical; if TRUE and if X is character, use X as names for the result unless it had names already.
n | number of replications.
expr | expression (language object, usually a call) to evaluate repeatedly.

Details

FUN is found by a call to match.fun and typically is specified as a function or a symbol (e.g. a backquoted name) or a character string specifying a function to be searched for from the environment of the call to lapply.

Function FUN must be able to accept as input any of the elements of X. If the latter is an atomic vector, FUN will always be passed a length-one vector of the same type as X.

Simplification in sapply is only attempted if X has length greater than zero and if the return values from all elements of X are all of the same (positive) length. If the common length is one the result is a vector, and if greater than one is a matrix with a column corresponding to each element of X.

The mode of the simplified answer is chosen to accommodate the modes of all the values returned by the calls to FUN: see unlist.

if X has length 0, the return value of sapply is always a 0-length list.

Note

sapply(*, simplify = FALSE, USE.NAMES = FALSE) is equivalent to lapply(*).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

apply, tapply, mapply for applying a function to multiple arguments, and rapply for a recursive version of lapply().

Examples

x <- list(a = 1:10, beta = exp(-3:3), logic = c(TRUE,FALSE,FALSE,TRUE))
# compute the list mean for each list element
lapply(x,mean)
# median and quartiles for each list element
lapply(x, quantile, probs = 1:3/4)
sapply(x, quantile)
i39 <- sapply(3:9, seq) # list of vectors
sapply(i39, fivenum)

hist(replicate(100, mean(rexp(10))))


Value of Last Evaluated Expression

Description

The value of the internal evaluation of a top-level R expression is always assigned to .Last.value (in package:base) before further processing (e.g., printing).

Usage

.Last.value

Details

The value of a top-level assignment is put in .Last.value, unlike S.

Do not assign to .Last.value in the workspace, because this will always mask the object of the same name in package:base.

See Also

eval

Examples

## These will not work correctly from example(),
## but they will in make check or if pasted in,
## as example() does not run them at the top level
gamma(1:15)          # think of some intensive calculation...
fac14 <- .Last.value # keep them

library("splines") # returns invisibly
.Last.value    # shows what library(.) above returned


Lazy Load a Database of R Objects

Description

Lazy load a database of R objects.

Usage

lazyLoad(filebase, envir = parent.frame(), filter)

Arguments

filebase | The file path to the database, with no extension.
envir | The environment into which objects are loaded.
filter | An optional function which when called on an object name returns TRUE or FALSE: only objects for which this is true will be loaded.

Details

This is the workhorse function called by the package loader to load the code for a package from a database. The database consists of two binary files, ‘filebase.rdb’ (the objects) and ‘filebase.rdx’ (an index).

The objects are not themselves loaded into envir: rather promises are created that will load the object from the database on first access. (See delayedAssign.)

Author(s)

Luke Tierney

See Also

makeLazyLoading


Length of an Object

Description

Get or set the length of vectors (including lists) and factors, and of any other R object for which a method has been defined.

Usage

length(x)
length(x) <- value

Arguments

x | an R object. For replacement, a vector or factor.
value | an integer.

Details

Both functions are generic: you can write methods to handle specific classes of objects, see InternalMethods. length<- has a "factor" method.

The replacement form can be used to reset the length of a vector. If a vector is shortened, extra values are discarded and when a vector is lengthened, it is padded out to its new length with NAs (nul for raw vectors).

Value

The default method currently returns an integer of length 1. Since this may change in the future and may differ for other methods, programmers should not rely on it. (Should the length exceed the maximum representable integer, it is returned as NA.)
For vectors (including lists) and factors the length is the number of elements. For an environment it is the number of objects in the environment, and NULL has length 0. For expressions and pairlists (including language objects and dotlists) it is the length of the pairlist chain. All other objects (including functions) have length one: note that for functions this differs from S.
The replacement form removes all the attributes of x except its names.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

nchar for counting the number of characters in character vectors.

Examples

length(diag(4))# = 16 (4 x 4)
length(options())# 12 or more
length(y ~ x1 + x2 + x3)# 3
length(expression(x, {y <- x^2; y+2}, x^y)) # 3

## from example(warpbreaks)
fm1 <- lm(breaks ~ wool * tension, data = warpbreaks)
length(fm1$call) # 3, lm() and two arguments.
length(formula(fm1)) # 3, ~ lhs rhs


Levels Attributes

Description

levels provides access to the levels attribute of a variable. The first form returns the value of the levels of its argument and the second sets the attribute.

The replacement form ("levels<-") of levels is a generic function and new methods can be written for it. The most important method is that for factors:

Usage

levels(x)
levels(x) <- value

Arguments

x | an object, for example a factor.
value | A valid value for levels(x). For the default method, NULL or a character vector. For the factor method, a vector of character strings with length at least the number of levels of x, or a named list specifying how to rename the levels.

Details

For the factor replacement method, a NA in value causes that level to be removed from the levels and the elements formerly with that level to be replaced by NA.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

nlevels, relevel, reorder.

Examples

## assign individual levels
x <- gl(2, 4, 8)
levels(x)[1] <- "low"
levels(x)[2] <- "high"
x

## or as a group
y <- gl(2, 4, 8)
levels(y) <- c("low", "high")
y

## combine some levels
z <- gl(3, 2, 12)
levels(z) <- c("A", "B", "A")
z

## same, using a named list
z <- gl(3, 2, 12)
levels(z) <- list(A=c(1,3), B=2)
z

## we can add levels this way:
f <- factor(c("a","b"))
levels(f) <- c("c", "a", "b")
f

f <- factor(c("a","b"))
levels(f) <- list(C="C", A="a", B="b")
f


Search Paths for Packages

Description

.libPaths gets/sets the library trees within which packages are looked for.

Usage

.libPaths(new)

.Library

Arguments

new a character vector with the locations of R library trees.

Details

.Library is a character string giving the location of the default library, the ‘library’ subdirectory of R_HOME.

.libPaths is used for getting or setting the library trees that R knows about (and hence uses when looking for packages). If called with argument new, the library search path is set to the existing files in unique(c(new, .Library)) and this is returned. If given no argument, a character vector with the currently known library trees is returned.

The library search path is initialized at startup from the environment variable R_LIBS (which should be a semicolon-separated list of directories at which R library trees are rooted) by calling .libPaths with the directories specified in R_LIBS.

Value

A character vector of file paths.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

library

Examples

.libPaths()                 # all library trees R knows about


Loading and Listing of Packages

Description

library and require load add-on packages.

.First.lib is called when a package is loaded; .Last.lib is called when a package is detached.

Usage

library(package, help, pos = 2, lib.loc = NULL,
        character.only = FALSE, logical.return = FALSE,
        warn.conflicts = TRUE,
        keep.source = getOption("keep.source.pkgs"),
        verbose = getOption("verbose"),
        version)

require(package, lib.loc = NULL, quietly = FALSE, warn.conflicts = TRUE,
        keep.source = getOption("keep.source.pkgs"),
        character.only = FALSE, version, save = TRUE)

.First.lib(libname, pkgname)
.Last.lib(libpath)

Arguments

package, help | the name of a package, given as a name or literal character string, or a character string, depending on whether character.only is FALSE (default) or TRUE).
pos | the position on the search list at which to attach the loaded package. Note that .First.lib may attach other packages, and pos is computed after .First.lib has been run. Can also be the name of a position on the current search list as given by search().
lib.loc | a character vector describing the location of R library trees to search through, or NULL. The default value of NULL corresponds to all libraries currently known. Non-existent library trees are silently ignored.
character.only | a logical indicating whether package or help can be assumed to be character strings.
version | A character string denoting a version number of the package to be loaded, for use with versioned installs: see the section later in this document.
logical.return | logical. If it is TRUE, FALSE or TRUE is returned to indicate success.
warn.conflicts | logical. If TRUE, warnings are printed about conflicts from attaching the new package, unless that package contains an object .conflicts.OK. A conflict is a function masking a function, or a non-function masking a non-function.
keep.source | logical. If TRUE, functions “keep their source” including comments, see argument keep.source to options. This applies only to the named package, and not to any packages or namespaces which might be loaded to satisfy dependencies or imports. This argument does not apply to packages using lazy-loading or saved images. Whether they have kept source is determined when they are installed (and is most likely false).
verbose | a logical. If TRUE, additional diagnostics are printed.
quietly | a logical. If TRUE, no message confirming package loading is printed.
save | logical or environment. If TRUE, a call to require from the source for a package will save the name of the required package in the variable ".required", allowing function detach to warn if a required package is detached. See section ‘Packages that require other packages’ below.
libname | a character string giving the library directory where the package was found.
pkgname | a character string giving the name of the package, including the version number if the package was installed with --with-package-versions.
libpath | a character string giving the complete path to the package.

Details

library(package) and require(package) both load the package with name package. require is designed for use inside other functions; it returns FALSE and gives a warning (rather than an error as library() does by default) if the package does not exist. Both functions check and update the list of currently loaded packages and do not reload a package which is already loaded.

If library is called with no package or help argument, it lists all available packages in the libraries specified by lib.loc, and returns the corresponding information in an object of class "libraryIQR". The structure of this class may change in future versions. In earlier versions of R, only the names of all available packages were returned; use .packages(all = TRUE) for obtaining these. Note that installed.packages() returns even more information.

library(help = somename) computes basic information about the package somename, and returns this in an object of class "packageInfo". The structure of this class may change in future versions. When used with the default value (NULL) for lib.loc, the loaded packages are searched before the libraries.

.First.lib is called when a package without a namespace is loaded by library. (For packages with namespaces see .onLoad.) It is called with two arguments, the name of the library directory where the package was found (i.e., the corresponding element of lib.loc), and the name of the package (in that order, and with the package name including the version for a versioned install, e.g. tree_1.0-16). It is a good place to put calls to library.dynam which are needed when loading a package into this function (don't call library.dynam directly, as this will not work if the package is not installed in a “standard” location). .First.lib is invoked after the search path interrogated by search() has been updated, so as.environment(match("package:name", search())) will return the environment in which the package is stored. If calling .First.lib gives an error the loading of the package is abandoned, and the package will be unavailable. Similarly, if the option ".First.lib" has a list element with the package's name, this element is called in the same manner as .First.lib when the package is loaded. This mechanism allows the user to set package “load hooks” in addition to startup code as provided by the package maintainers, but setHook is preferred.

.Last.lib is called when a package is detached. Beware that it might be called if .First.lib has failed, so it should be written defensively. (It is called within try, so errors will not stop the package being detached.)

Value

library returns the list of loaded (or available) packages (or TRUE if logical.return is TRUE). require returns a logical indicating whether the required package is available.

Packages that require other packages

NB: This mechanism has been almost entirely superseded by using the Depends: field in the ‘DESCRIPTION’ file of a package.

The source code for a package that requires one or more other packages should have a call to require, preferably near the beginning of the source, and of course before any code that uses functions, classes or methods from the other package. The default for argument save will save the names of all required packages in the environment of the new package. The saved package names are used by detach when a package is detached to warn if other packages still require the to-be-detached package. Also, if a package is installed with saved image (see INSTALL), the saved package names are used to require these packages when the new package is attached.

Formal methods

library takes some further actions when package methods is attached (as it is by default). Packages may define formal generic functions as well as re-defining functions in other packages (notably base) to be generic, and this information is cached whenever such a package is loaded after methods and re-defined functions are excluded from the list of conflicts. The check requires looking for a pattern of objects; the pattern search may be avoided by defining an object .noGenerics (with any value) in the package. Naturally, if the package does have any such methods, this will prevent them from being used.

Versioned installs

Packages can be installed with version information by R CMD INSTALL --with-package-versions or install.packages(installWithVers = TRUE). This allows more than one version of a package to be installed in a library directory, using package directory names like foo_1.5-1. When such packages are loaded, it is this versioned name that search() returns. Some utility functions require the versioned name and some the unversioned name (here foo).

If version is not specified, library looks first for a packages of that name, and then for versioned installs of the package, selecting the one with the latest version number. If version is specified, a versioned install with an exactly matching version is looked for.

If version is not specified, require will accept any version that is already loaded, whereas library will look for an unversioned install even if a versioned install is already loaded.

Loading more than one version of a package into an R session is not currently supported. Support for versioned installs is patchy.

Note

library and require can only load an installed package, and this is detected by having a ‘DESCRIPTION’ file containing a Built: field.

Under Unix-alikes, the code checks that the package was installed under a similar operating system as given by R.version$platform (the canonical name of the platform under which R was compiled), provided it contains compiled code. Packages which do not contain compiled code can be shared between Unix-alikes, but not to other OSes because of potential problems with line endings and OS-specific help files.

The package name given to library and require must match the name given in the package's ‘DESCRIPTION’ file exactly, even on case-insensitive file systems such as MS Windows.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

.libPaths, .packages.

attach, detach, search, objects, autoload, library.dynam, data, install.packages and installed.packages; INSTALL, REMOVE.

Examples

library()                   # list all available packages
library(lib = .Library)     # list all packages in the default library
library(help = splines)     # documentation on package 'splines'
library(splines)            # load package 'splines'
require(splines)            # the same
search()                    # "splines", too
detach("package:splines")

# if the package name is in a character vector, use
pkg <- "splines"
library(pkg, character.only = TRUE)
detach(pos = match(paste("package", pkg, sep=":"), search()))

require(pkg, character.only = TRUE)
detach(pos = match(paste("package", pkg, sep=":"), search()))

require(nonexistent)        # FALSE
## Not run:
## Suppose a package needs to call a shared library named 'fooEXT',
## where 'EXT' is the system-specific extension.  Then you should use
.First.lib <- function(lib, pkg) {
  library.dynam("foo", pkg, lib)
}

## if you want to mask as little as possible, use
library(mypkg, pos = "package:base")
## End(Not run)


Loading Shared Libraries

Description

Load the specified file of compiled code if it has not been loaded already, or unloads it.

Usage

library.dynam(chname, package = NULL, lib.loc = NULL,
              verbose = getOption("verbose"),
              file.ext = .Platform$dynlib.ext, ...)

library.dynam.unload(chname, libpath,
              verbose = getOption("verbose"),
              file.ext = .Platform$dynlib.ext)

.dynLibs(new)

Arguments

chname | a character string naming a shared library to load.
package | a character vector with the names of packages to search through, or NULL. By default, all packages in the search path are used.
lib.loc | a character vector describing the location of R library trees to search through, or NULL. The default value of NULL corresponds to all libraries currently known.
libpath | the path to the loaded package whose shared library is to be unloaded.
verbose | a logical value indicating whether an announcement is printed on the console before loading the shared library. The default value is taken from the verbose entry in the system options.
file.ext | the extension to append to the file name to specify the library to be loaded. This defaults to the appropriate value for the operating system.
... | additional arguments needed by some libraries that are passed to the call to dyn.load to control how the library is loaded.
new | a list of "DLLInfo" objects corresponding to the shared libraries loaded by packages. Can be missing.

Details

library.dynam is designed to be used inside a package rather than at the command line, and should really only be used inside .First.lib or .onLoad. The system-specific extension for shared libraries (‘.dll’ on Windows) should not be added. Note that to allow for versioned installs, the chname argument should not be set to the pkgname argument of .First.lib or .onLoad.

library.dynam.unload is designed for use in .Last.lib or .onUnload: it unloads the shared object and updates the value of .dynLibs()

.dynLibs is used for getting (with no argument) or setting the shared libraries which are currently loaded by packages (using library.dynam).

Value

If chname is not specified, library.dynam returns an object of class "DLLInfoList" corresponding to the shared libraries loaded by packages.
If chname is specifed, an object of class "DLLInfo" that identifies the DLL and can be used in future calls is returned invisibly. For packages that have namespaces, a list of these objects is stored in the namespace's environment for use at run-time.
Note that the class DLLInfo has an overloaded method for $ which can be used to resolve native symbols within that DLL.
library.dynam.unload invisibly returns an object of class "DLLInfo" identifying the DLL successfully unloaded.
.dynLibs returns an object of class "DLLInfoList" corresponding corresponding to its current value.

Warning

Do not use dyn.unload on a shared object loaded by library.dynam: use library.dynam.unload to ensure that .dynLibs gets updated. Otherwise a subsequent call to library.dynam will be told the object is already loaded.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

getLoadedDLLs for information on "DLLInfo" and "DLLInfoList" objects.

.First.lib, library, dyn.load, .packages, .libPaths

SHLIB for how to create suitable DLLs.

Examples

## Which DLLs were "dynamically loaded" by packages?
library.dynam()


The R License Terms

Description

The license terms under which R is distributed.

Usage

license()
licence()

Details

R is distributed under the terms of the GNU GENERAL PUBLIC LICENSE Version 2, June 1991. A copy of this license is in ‘$R_HOME/COPYING’.

A small number of files (the API header files and import library) are distributed under the LESSER GNU GENERAL PUBLIC LICENSE version 2.1. A copy of this license is in ‘$R_HOME/COPYING.LIB’.


Lists – Generic and Dotted Pairs

Description

Functions to construct, coerce and check for both kinds of R lists.

Usage

list(...)
pairlist(...)

as.list(x, ...)
## S3 method for class 'environment':
as.list(x, all.names = FALSE, ...)
as.pairlist(x)

is.list(x)
is.pairlist(x)

alist(...)

Arguments

... | objects, possibly named.
x | object to be coerced or tested.
all.names | a logical indicating whether to copy all values or (default) only those whose names do not begin with a dot.

Details

Most lists in R internally are Generic Vectors, whereas traditional dotted pair lists (as in LISP) are available but rarely seen by users (except as formals of functions).

The arguments to list or pairlist are of the form value or tag=value. The functions return a list or dotted pair list composed of its arguments with each value either tagged or untagged, depending on how the argument was specified.

alist handles its arguments as if they described function arguments. So the values are not evaluated, and tagged arguments with no value are allowed whereas list simply ignores them. alist is most often used in conjunction with formals.

as.list attempts to coerce its argument to a list. For functions, this returns the concatenation of the list of formal arguments and the function body. For expressions, the list of constituent calls is returned. as.list is generic, and as the default method calls as.vector(mode="list") methods for as.vector may be invoked. As from R 2.4.0, as.list turns a factor into a list of one-element factors. All attributes will be dropped unless the argument already is a list. (This is inconsistent with functions such as as.character, and is for efficiency since lists can be expensive to copy.)

is.list returns TRUE iff its argument is a list or a pairlist of length > 0. is.pairlist returns TRUE iff the argument is a pairlist or NULL (see below).

is.list and is.pairlist are generic: you can write methods to handle specific classes of objects, see InternalMethods.

The "environment" method for as.list copies the name-value pairs (for names not beginning with a dot) from an environment to a named list. The user can request that all named objects are copied. The list is in no particular order (the order depends on the order of creation of objects and whether the environmnent is hashed). No parent environments are searched. (Objects copied are duplicated so this can be an expensive operation.)

An empty pairlist, pairlist() is the same as NULL. This is different from list().

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

vector("list", length) for creation of a list with empty components; c, for concatenation; formals.

Examples

# create a plotting structure
pts <- list(x=cars[,1], y=cars[,2])
plot(pts)

is.pairlist(.Options)  # a user-level pairlist

## "pre-allocate" an empty list of length 5
vector("list", 5)

# Argument lists
f <- function() x
# Note the specification of a "..." argument:
formals(f) <- al <- alist(x=, y=2+3, ...=)
f
al

## environment->list coercion

e1 <- new.env()
e1$a <- 10
e1$b <- 20
as.list(e1)


List the Files in a Directory/Folder

Description

These functions produce a character vector of the names of files in the named directory.

Usage

list.files(path = ".", pattern = NULL, all.files = FALSE,
           full.names = FALSE, recursive = FALSE)
       dir(path = ".", pattern = NULL, all.files = FALSE,
           full.names = FALSE, recursive = FALSE)

Arguments

path | a character vector of full path names; the default corresponds to the working directory getwd().
pattern | an optional regular expression. Only file names which match the regular expression will be returned.
all.files | a logical value. If FALSE, only the names of visible files are returned. If TRUE, all file names will be returned.
full.names | a logical value. If TRUE, the directory path is prepended to the file names. If FALSE, only the file names are returned.
recursive | logical. Should the listing recurse into directories?

Value

A character vector containing the names of the files in the specified directories, or "" if there were no files. If a path does not exist or is not a directory or is unreadable it is skipped, with a warning.
The files are sorted in alphabetical order, on the full path if full.names = TRUE.

Note

File naming conventions are very platform dependent.

recursive = TRUE is not supported on all platforms, and may be ignored, with a warning.

Author(s)

Ross Ihaka, Brian Ripley

See Also

file.info, file.access and files for many more file handling functions and file.choose and choose.files for interactive selection.

glob2rx to convert wildcards (as used by system file commands and shells) to regular expressions.

Examples

list.files(R.home())
## Only files starting with a-l or r (*including* uppercase):
dir("../..", pattern = "^[a-lr]",full.names=TRUE)


Reload Saved Datasets

Description

Reload datasets written with the function save.

Usage

load(file, envir = parent.frame())

Arguments

file | a (readable binary) connection or a character string giving the name of the file to load.
envir | the environment where the data should be loaded.

Details

load can load R objects saved in the current or any earlier format. It can read a compressed file (see save) directly from a file or from a suitable connection (including a call to url).

Only R objects saved in the current format (used since R 1.4.0) can be read from a connection. If no input is available on a connection a warning will be given, but any input not in the current format will result in a error.

Loading from an earlier version will give a warning about the ‘magic number’: magic numbers 1971:1977 are from R < 0.99.0, and R[ADX]1 from R 0.99.0 to R 1.3.1.

Value

A character vector of the names of objects created, invisibly.

Warning

Saved R objects are binary files, even those saved with ascii = TRUE, so ensure that they are transferred without conversion of end of line markers. load tries to detect this case and give an informative error message.

Note

Prior to R 2.4.0 an object saved as a pairlist was coerced to a list, silently (and undocumented).

See Also

save, download.file.

Examples

## save all data
xx <- pi # to ensure there is some data
save(list = ls(all=TRUE), file= "all.Rdata")
rm(xx)

## restore the saved values to the current environment
local({
   load("all.Rdata")
   ls()
})
## restore the saved values to the user's workspace
load("all.Rdata", .GlobalEnv)

unlink("all.Rdata")

## Not run:
con <- url("http://some.where.net/R/data/kprats.rda")
## print the value to see what objects were created.
print(load(con))
close(con)
## End(Not run)


Find Details of the Numerical and Monetary Representations in the Current Locale

Description

Get details of the numerical and monetary representations in the current locale.

Usage

Sys.localeconv()

Details

These settings are usually controlled by the environment variables LC_NUMERIC and LC_MONETARY and if not set the values of LC_ALL or LANG.

Normally R is run without looking at the value of LC_NUMERIC, so the decimal point remains '.'. So the first three of these values will not be useful unless you have set LC_NUMERIC in the current R session.

Value

A character vector with 18 named components. See your ISO C documentation for details of the meaning.
It is possible to compile R without support for locales, in which case the value will be NULL.

See Also

Sys.setlocale for ways to set locales.

Examples

Sys.localeconv()
## The results in the C locale are
##    decimal_point     thousands_sep          grouping   int_curr_symbol
##              "."                ""                ""                ""
##  currency_symbol mon_decimal_point mon_thousands_sep      mon_grouping
##               ""                ""                ""                ""
##    positive_sign     negative_sign   int_frac_digits       frac_digits
##               ""                ""             "127"             "127"
##    p_cs_precedes    p_sep_by_space     n_cs_precedes    n_sep_by_space
##            "127"             "127"             "127"             "127"
##      p_sign_posn       n_sign_posn
##            "127"             "127"

## Now try your default locale (which might be "C").
## Not run:
old <- Sys.getlocale()
Sys.setlocale(locale = "")
Sys.localeconv()
Sys.setlocale(locale = old)
## End(Not run)

## Not run: read.table("foo", dec=Sys.localeconv()["decimal_point"])


Query or Set Aspects of the Locale

Description

Get details of or set aspects of the locale for the R process.

Usage

Sys.getlocale(category = "LC_ALL")
Sys.setlocale(category = "LC_ALL", locale = "")

Arguments

category | character string. The following categories should always be supported: "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MONETARY", "LC_NUMERIC" and "LC_TIME". Some systems (not Windows) will also support "LC_MESSAGES", "LC_PAPER" and "LC_MEASUREMENT".
locale | character string. A valid locale name on the system in use. Normally "" (the default) will pick up the default locale for the system.

Details

The locale describes aspects of the internationalization of a program. Initially most aspects of the locale of R are set to "C" (which is the default for the C language and reflects North-American usage). R sets "LC_CTYPE" and "LC_COLLATE", which allow the use of a different character set and alphabetic comparisons in that character set (including the use of sort), "LC_MONETARY" (for use by Sys.localeconv) and "LC_TIME" may affect the behaviour of as.POSIXlt and strptime and functions which use them (but not date).

R can be built with no support for locales, but it is normally available on Unix and is available on Windows.

The first seven categories described here are those specified by POSIX. "LC_MESSAGES" will be "C" on systems that do not support message translation, and is not supported on Windows. Trying to use an unsupported category is an error for Sys.setlocale.

Note that setting "LC_ALL" sets only "LC_COLLATE", "LC_CTYPE", "LC_MONETARY" and "LC_TIME".

Value

A character string of length one describing the locale in use (after setting for Sys.setlocale), or an empty character string if the locale is invalid (with a warning) or NULL if locale information is unavailable.
For category = "LC_ALL" the details of the string are system-specific: it might be a single locale or a set of locales separated by "/" (Solaris) or ";" (Windows, Linux). For portability, it is best to query categories individually. It is guaranteed that the result of foo <- Sys.getlocale() can be used in Sys.setlocale("LC_ALL", locale = foo) on the same machine.

Warning

Setting "LC_CTYPE" to "C" causes problems in the C code, so it is interpreted as an English locale in CP1252.

Setting "LC_NUMERIC" may cause R to function anomalously, so gives a warning. (The known problems are with input conversion in locales with , as the decimal point.) Setting it temporarily to produce graphical or text output may work well enough, but options(OutDec) is often preferable.

See Also

strptime for uses of category = "LC_TIME". Sys.localeconv for details of numerical and monetary representations.

Examples

Sys.getlocale()
Sys.getlocale("LC_TIME")
## Not run:
Sys.setlocale("LC_TIME", "de")     # Solaris: details are OS-dependent
Sys.setlocale("LC_TIME", "German") # Windows
## End(Not run)
Sys.getlocale("LC_PAPER")          # may or may not be set

Sys.setlocale("LC_COLLATE", "C")   # turn off locale-specific sorting


Logarithms and Exponentials

Description

log computes natural logarithms, log10 computes common (i.e., base 10) logarithms, and log2 computes binary (i.e., base 2) logarithms. The general form logb(x, base) computes logarithms with base base.

log1p(x) computes log(1+x) accurately also for |x| << 1 (and less accurately when x is approximately -1).

exp computes the exponential function.

expm1(x) computes exp(x) - 1 accurately also for |x| << 1.

Usage

log(x, base = exp(1))
logb(x, base = exp(1))
log10(x)
log2(x)

exp(x)
expm1(x)

log1p(x)

Arguments

x | a numeric or complex vector.
base | positive number. The base with respect to which logarithms are computed. Defaults to e=exp(1).

Details

exp and log are generic functions: methods can be defined for them individually or via the Math group generic.

log10 and log2 are only special cases, but will be computed more efficiently and accurately where supported by the OS.

Value

A vector of the same length as x containing the transformed values. log(0) gives -Inf (when available).

Note

log and logb are the same thing in R, but logb is preferred if base is specified, for S-PLUS compatibility.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole. (for log, \log10 and exp.)

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language. Springer. (for logb.)

See Also

Trig, sqrt, Arithmetic.

Examples

log(exp(3))
log10(1e7)# = 7

x <- 10^-(1+2*1:9)
cbind(x, log(1+x), log1p(x), exp(x)-1, expm1(x))


Logical Operators

Description

These operators act on logical vectors.

Usage

! x
x & y
x && y
x | y
x || y
xor(x, y)

isTRUE(x)

Arguments

x, y logical vectors, or objects which can be coerced to such or for which methods have been written.

Details

! indicates logical negation (NOT).

& and && indicate logical AND and | and || indicate logical OR. The shorter form performs elementwise comparisons in much the same way as arithmetic operators. The longer form evaluates left to right examining only the first element of each vector. Evaluation proceeds only until the result is determined. The longer form is appropriate for programming control-flow and typically preferred in if clauses.

xor indicates elementwise exclusive OR.

isTRUE(x) is an abbreviation of identical(TRUE, x), and so is true if and only if x is a length-one logical vector with no attributes (not even names).

Numeric and complex vectors will be coerced to logical values, with zero being false and all non-zero values being true. Raw vectors are handled without any coercion for !, & and |, with these operators being applied bitwise (so ! is the 1-complement).

The operators !, & and | are generic functions: methods can be written for them individually or via the Ops) group generic function. (See Ops for how dispatch is computed.)

NA is a valid logical object. Where a component of x or y is NA, the result will be NA if the outcome is ambiguous. In other words NA & TRUE evaluates to NA, but NA & FALSE evaluates to FALSE. See the examples below.

See Syntax for the precedence of these operators: unlike many other languages (including S) the AND and OR operators do not have the same precedence (the AND operators are higher than the OR operators).

Value

For !, a logical or raw vector of the same length as x.
For |, & and xor a logical or raw vector. The elements of shorter vectors are recycled as necessary (with a warning when they are recycled only fractionally). The rules for determining the attributes of the result are rather complicated. Most attributes are taken from the longer argument, the first if they are of the same length. Names will be copied from the first if it is the same length as the answer, otherwise from the second if that is. For time series, these operations are allowed only if the series are compatible, when the class and tsp attribute of whichever is a time series (the same, if both are) are used. For arrays (and an array result) the dimensions and dimnames are taken from first argument if it is an array, otherwise the second.
For ||, && and isTRUE, a length-one logical vector.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

TRUE or logical.

any and all for OR and AND on many scalar arguments.

Syntax for operator precedence.

Examples

y <- 1 + (x <- rpois(50, lambda=1.5) / 4 - 1)
x[(x > 0) & (x < 1)]    # all x values between 0 and 1
if (any(x == 0) || any(y == 0)) "zero encountered"

## construct truth tables :

x <- c(NA, FALSE, TRUE)
names(x) <- as.character(x)
outer(x, x, "&")## AND table
outer(x, x, "|")## OR  table


Logical Vectors

Description

Create or test for objects of type "logical", and the basic logical “constants”.

Usage

TRUE
FALSE
T; F

logical(length = 0)
as.logical(x, ...)
is.logical(x)

Arguments

length | desired length.
x | object to be coerced or tested.
... | further arguments passed to or from other methods.

Details

TRUE and FALSE are part of the R language, where T and F are global variables set to these. All four are logical(1) vectors.

is.logical is generic: you can write methods to handle specific classes of objects, see InternalMethods.

Value

logical creates a logical vector of the specified length. Each element of the vector is equal to FALSE.
as.logical attempts to coerce its argument to be of logical type. For factors, this uses the levels (labels). Like as.vector it strips attributes including names.
is.logical returns TRUE or FALSE depending on whether its argument is of logical type or not.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.


Lower and Upper Triangular Part of a Matrix

Description

Returns a matrix of logicals the same size of a given matrix with entries TRUE in the lower or upper triangle.

Usage

lower.tri(x, diag = FALSE)
upper.tri(x, diag = FALSE)

Arguments

x | a matrix.
diag | logical. Should the diagonal be included?

See Also

diag, matrix.

Examples

(m2 <- matrix(1:20, 4, 5))
lower.tri(m2)
m2[lower.tri(m2)] <- NA
m2


List Objects

Description

ls and objects return a vector of character strings giving the names of the objects in the specified environment. When invoked with no argument at the top level prompt, ls shows what data sets and functions a user has defined. When invoked with no argument inside a function, ls returns the names of the functions local variables. This is useful in conjunction with browser.

Usage

ls(name, pos = -1, envir = as.environment(pos),
   all.names = FALSE, pattern)
objects(name, pos= -1, envir = as.environment(pos),
        all.names = FALSE, pattern)

Arguments

name | which environment to use in listing the available objects. Defaults to the current environment. Although called name for back compatibility, in fact this argument can specify the environment in any form; see the details section.
pos | An alternative argument to name for specifying the environment as a position in the search list. Mostly there for back compatibility.
envir | an alternative argument to name for specifying the environment evaluation environment. Mostly there for back compatibility.
all.names | a logical value. If TRUE, all object names are returned. If FALSE, names which begin with a . are omitted.
pattern | an optional regular expression. Only names matching pattern are returned. glob2rx can be used to convert wildcard patterns to regular expressions.

Details

The name argument can specify the environment from which object names are taken in one of several forms: as an integer (the position in the search list); as the character string name of an element in the search list; or as an explicit environment (including using sys.frame to access the currently active function calls). By default, the environment of the call to ls or objects is used. The pos and envir arguments are an alternative way to specify an environment, but are primarily there for back compatibility.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

glob2rx for converting wildcard patterns to regular expressions.

ls.str for a long listing based on str. apropos (or find) for finding objects in the whole search path; grep for more details on “regular expressions”; class, methods, etc., for object-oriented programming.

Examples

.Ob <- 1
ls(pat="O")
ls(pat="O", all = TRUE)    # also shows ".[foo]"

# shows an empty list because inside myfunc no variables are defined
myfunc <- function() {ls()}
myfunc()

# define a local variable inside myfunc
myfunc <- function() {y <- 1; ls()}
myfunc()                # shows "y"


Make Syntactically Valid Names

Description

Make syntactically valid names out of character vectors.

Usage

make.names(names, unique = FALSE, allow_ = TRUE)

Arguments

names | character vector to be coerced to syntactically valid names. This is coerced to character if necessary.
unique | logical; if TRUE, the resulting elements are unique. This may be desired for, e.g., column names.
allow_ | logical. For compatibility with R prior to 1.9.0.

Details

A syntactically valid name consists of letters, numbers and the dot or underline characters and starts with a letter or the dot not followed by a number. Names such as ".2way" are not valid, and neither are the reserved words.

The character "X" is prepended if necessary. All invalid characters are translated to ".". A missing value is translated to "NA". Names which match R keywords have a dot appended to them. Duplicated values are altered by make.unique.

Value

A character vector of same length as names with each changed to a syntactically valid name.

Note

Prior to R version 1.9.0, underscores were not valid in variable names, and code that relies on them being converted to dots will no longer work. Use allow_ = FALSE for back-compatibility.

allow_ = FALSE is also useful when creating names for export to applications which do not allow underline in names (for example, S-PLUS and some DBMSs).

See Also

make.unique, names, character, data.frame.

Examples

make.names(c("a and b", "a-and-b"), unique=TRUE)
# "a.and.b"  "a.and.b.1"
make.names(c("a and b", "a_and_b"), unique=TRUE)
# "a.and.b"  "a_and_b"
make.names(c("a and b", "a_and_b"), unique=TRUE, allow_=FALSE)
# "a.and.b"  "a.and.b.1"

state.name[make.names(state.name) != state.name] # those 10 with a space


Make Character Strings Unique

Description

Makes the elements of a character vector unique by appending sequence numbers to duplicates.

Usage

make.unique(names, sep = ".")

Arguments

names | a character vector
sep | a character string used to separate a duplicate name from its sequence number.

Details

The algorithm used by make.unique has the property that make.unique(c(A, B)) == make.unique(c(make.unique(A), B)).

In other words, you can append one string at a time to a vector, making it unique each time, and get the same result as applying make.unique to all of the strings at once.

If character vector A is already unique, then make.unique(c(A, B)) preserves A.

Value

A character vector of same length as names with duplicates changed.

Author(s)

Thomas P Minka

See Also

make.names

Examples

make.unique(c("a", "a", "a"))
make.unique(c(make.unique(c("a", "a")), "a"))

make.unique(c("a", "a", "a.2", "a"))
make.unique(c(make.unique(c("a", "a")), "a.2", "a"))

rbind(data.frame(x=1), data.frame(x=2), data.frame(x=3))
rbind(rbind(data.frame(x=1), data.frame(x=2)), data.frame(x=3))


Mangle the Package Name

Description

This function takes the package name and the package version number and pastes them together with a separating underscore.

Usage

manglePackageName(pkgName, pkgVersion)

Arguments

pkgName | The package name, as a character string.
pkgVersion | The package version, as a character string.

Value

A character string with the two inputs pasted together.

Examples

  manglePackageName("foo", "1.2.3")


Apply a function to multiple list or vector arguments

Description

mapply is a multivariate version of sapply. mapply applies FUN to the first elements of each ... argument, the second elements, the third elements, and so on. Arguments are recycled if necessary.

Vectorize returns a new function that acts as if mapply was called.

Usage

mapply(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE,
       USE.NAMES = TRUE)

Vectorize(FUN, vectorize.args = arg.names, SIMPLIFY = TRUE,
          USE.NAMES = TRUE)

Arguments

FUN | function to apply, found via match.fun.
... | arguments to vectorise over (list or vector).
MoreArgs | a list of other arguments to FUN.
SIMPLIFY | logical; attempt to reduce the result to a vector or matrix?
USE.NAMES | logical; use names if the first ... argument has names, or if it is a character vector, use that character vector as the names.
vectorize.args | a character vector of arguments which should be vectorized. Defaults to all arguments to FUN.

Details

The arguments named in the vectorize.args argument to Vectorize correspond to the arguments passed in the ... list to mapply. However, only those that are actually passed will be vectorized; default values will not. See the example below.

Vectorize cannot be used with primitive functions as they have no formal list.

Value

mapply returns a list, vector, or matrix.
Vectorize returns a function with the same arguments as FUN, but wrapping a call to mapply.

See Also

sapply, outer

Examples

mapply(rep, 1:4, 4:1)

mapply(rep, times=1:4, x=4:1)

mapply(rep, times=1:4, MoreArgs=list(x=42))

# Repeat the same using Vectorize: use rep.int as rep is primitive
vrep <- Vectorize(rep.int)
vrep(1:4, 4:1)
vrep(times=1:4, x=4:1)

vrep <- Vectorize(rep.int, "times")
vrep(times=1:4, x=42)

mapply(function(x,y) seq_len(x) + y,
       c(a= 1, b=2, c= 3),  # names from first
       c(A=10, B=0, C=-10))

word <- function(C,k) paste(rep.int(C,k), collapse='')
str(mapply(word, LETTERS[1:6], 6:1, SIMPLIFY = FALSE))

f <- function(x=1:3, y) c(x,y)
vf <- Vectorize(f, SIMPLIFY = FALSE)
f(1:3,1:3)
vf(1:3,1:3)
vf(y=1:3) # Only vectorizes y, not x

# Nonlinear regression contour plot, based on nls() example

SS <- function(Vm, K, resp, conc) {
    pred <- (Vm * conc)/(K + conc)
    sum((resp - pred)^2 / pred)
}
vSS <- Vectorize(SS, c("Vm", "K"))
Treated <- subset(Puromycin, state == "treated")

Vm <- seq(140, 310, len=50)
K <- seq(0, 0.15, len=40)
SSvals <- outer(Vm, K, vSS, Treated$rate, Treated$conc)
contour(Vm, K, SSvals, levels=(1:10)^2, xlab="Vm", ylab="K")


Compute table margin

Description

For a contingency table in array form, compute the sum of table entries for a given index.

Usage

margin.table(x, margin=NULL)

Arguments

x | an array
margin | index number (1 for rows, etc.)

Details

This is really just apply(x, margin, sum) packaged up for newbies, except that if margin has length zero you get sum(x).

Value

The relevant marginal table. The class of x is copied to the output table, except in the summation case.

Author(s)

Peter Dalgaard

See Also

prop.table and addmargins.

Examples

m <- matrix(1:4,2)
margin.table(m,1)
margin.table(m,2)


Create a Matrix or a Vector

Description

mat.or.vec creates an nr by nc zero matrix if nc is greater than 1, and a zero vector of length nr if nc equals 1.

Usage

mat.or.vec(nr, nc)

Arguments

nr, nc numbers of rows and columns.

Examples

mat.or.vec(3, 1)
mat.or.vec(3, 2)


Value Matching

Description

match returns a vector of the positions of (first) matches of its first argument in its second.

%in% is a more intuitive interface as a binary operator, which returns a logical vector indicating if there is a match or not for its left operand.

Usage

match(x, table, nomatch = NA, incomparables = FALSE)

x %in% table

Arguments

x | vector or NULL: the values to be matched.
table | vector or NULL: the values to be matched against.
nomatch | the value to be returned in the case when no match is found. Note that it is coerced to integer.
incomparables | a vector of values that cannot be matched. Any value in x matching a value in this vector is assigned the nomatch value. Currently, FALSE is the only possible value, meaning that all values can be matched.

Details

%in% is currently defined as
"%in%" <- function(x, table) match(x, table, nomatch = 0) > 0

Factors, raw vectors and lists are converted to character vectors, and then x and table are coerced to a common type (the later of the two types in R's ordering, logical < integer < numeric < complex < character) before matching.

Matching for lists is potentially very slow and best avoided except in simple cases.

Exactly what matches what is to some extent a matter of definition. For all types, NA matches NA and no other value. For real and complex values, NaN values are regarded as matching any other NaN value, but not matching NA.

Value

A vector of the same length as x.
match: An integer vector giving the position in table of the first match if there is a match, otherwise nomatch.
If x[i] is found to equal table[j] then the value returned in the i-th position of the return value is j, for the smallest possible j. If no match is found, the value is nomatch.
%in%: A logical vector, indicating if a match was located for each element of x.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

pmatch and charmatch for (partial) string matching, match.arg, etc for function argument matching. findInterval similarly returns a vector of positions, but finds numbers within intervals, rather than exact matches.

is.element for an S-compatible equivalent of %in%.

Examples

## The intersection of two sets :
intersect <- function(x, y) y[match(x, y, nomatch = 0)]
intersect(1:10,7:20)

1:10 %in% c(1,3,5,9)
sstr <- c("c","ab","B","bba","c","@","bla","a","Ba","%")
sstr[sstr %in% c(letters,LETTERS)]

"%w/o%" <- function(x,y) x[!x %in% y] #--  x without y
(1:10) %w/o% c(3,7,12)


Argument Verification Using Partial Matching

Description

match.arg matches arg against a table of candidate values as specified by choices.

Usage

match.arg(arg, choices, several.ok = FALSE)

Arguments

arg | a character string
choices | a character vector of candidate values
several.ok | logical specifying if arg should be allowed to have more than one element.

Details

In the one-argument form match.arg(arg), the choices are obtained from a default setting for the formal argument arg of the function from which match.arg was called.

Matching is done using pmatch, so arg may be abbreviated.

Value

The unabbreviated version of the unique partial match if there is one; otherwise, an error is signalled if several.ok is false, as per default. When several.ok is true and there is more than one match, all unabbreviated versions of matches are returned.

See Also

pmatch, match.fun, match.call.

Examples

require(stats)
## Extends the example for 'switch'
center <- function(x, type = c("mean", "median", "trimmed")) {
  type <- match.arg(type)
  switch(type,
         mean = mean(x),
         median = median(x),
         trimmed = mean(x, trim = .1))
}
x <- rcauchy(10)
center(x, "t")       # Works
center(x, "med")     # Works
try(center(x, "m"))  # Error

## Allowing more than one match:
match.arg(c("gauss", "rect", "ep"),
          c("gaussian", "epanechnikov", "rectangular", "triangular"),
          several.ok = TRUE)


Argument Matching

Description

match.call returns a call in which all of the specified arguments are specified by their full names.

Usage

match.call(definition = NULL, call = sys.call(sys.parent()),
           expand.dots = TRUE)

Arguments

definition | a function, by default the function from which match.call is called.
call | an unevaluated call to the function specified by definition, as generated by call.
expand.dots | logical. Should arguments matching ... in the call be included or left as a ... argument?

Details

match.call is most commonly used in two circumstamces:

  • To record the call for later re-use: for example most model-fitting functions record the call as element call of the list they return. Here the default expand.dots = TRUE is appropriate.
  • To pass most of the call to another function, often model.frame. Here the common idiom is that expand.dots = FALSE is used, and the ... elememt of the matched call is removed. An alternative is to explicitly select the arguments to be passed on, as is done in lm.

Value

An object of class call.

References

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language. Springer.

See Also

call, pmatch, match.arg, match.fun.

Examples

match.call(get, call("get", "abc", i = FALSE, p = 3))
## -> get(x = "abc", pos = 3, inherits = FALSE)
fun <- function(x, lower = 0, upper = 1) {
  structure((x - lower) / (upper - lower), CALL = match.call())
}
fun(4 * atan(1), u = pi)


Function Verification for “Function Variables”

Description

When called inside functions that take a function as argument, extract the desired function object while avoiding undesired matching to objects of other types.

Usage

match.fun(FUN, descend = TRUE)

Arguments

FUN | item to match as function: a function, symbol or character string. See Details.
descend | logical; control whether to search past non-function objects.

Details

match.fun is not intended to be used at the top level since it will perform matching in the parent of the caller.

If FUN is a function, it is returned. If it is a symbol (for example, enclosed in backquotes) or a character vector of length one, it will be looked up using get in the environment of the parent of the caller. If it is of any other mode, it is attempted first to get the argument to the caller as a symbol (using substitute twice), and if that fails, an error is declared.

If descend = TRUE, match.fun will look past non-function objects with the given name; otherwise if FUN points to a non-function object then an error is generated.

This is used in base functions such as apply, lapply, outer, and sweep.

Value

A function matching FUN or an error is generated.

Bugs

The descend argument is a bit of misnomer and probably not actually needed by anything. It may go away in the future.

It is impossible to fully foolproof this. If one attaches a list or data frame containing a length-one character vector with the same name as a function, it may be used (although namespaces will help).

Author(s)

Peter Dalgaard and Robert Gentleman, based on an earlier version by Jonathan Rougier.

See Also

match.arg, get

Examples

# Same as get("*"):
match.fun("*")
# Overwrite outer with a vector
outer <- 1:5
## Not run:
match.fun(outer, descend = FALSE) #-> Error:  not a function
## End(Not run)
match.fun(outer) # finds it anyway
is.function(match.fun("outer")) # as well


Miscellaneous Mathematical Functions

Description

These functions compute miscellaneous mathematical functions. The naming follows the standard for computer languages such as C or Fortran.

Usage

abs(x)
sqrt(x)

Arguments

x a numeric or complex vector or array.

Details

These are generic functions: methods can be defined for them individually or via the Math group generic. For complex arguments (and the default method), z, abs(z) == Mod(z) and sqrt(z) == z^0.5.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

Arithmetic for simple, log for logarithmic, sin for trigonometric, and Special for special mathematical functions.

Examples

require(stats) # for spline
xx <- -9:9
plot(xx, sqrt(abs(xx)),  col = "red")
lines(spline(xx, sqrt(abs(xx)), n=101), col = "pink")


Matrix Multiplication

Description

Multiplies two matrices, if they are conformable. If one argument is a vector, it will be promoted to either a row or column matrix to make the two arguments conformable. If both are vectors it will return the inner product.

Usage

a %*% b

Arguments

a, b numeric or complex matrices or vectors.

Details

When a vector is promoted to a matrix, its names are not promoted to row or column names, unlike as.matrix.

Value

The matrix product. Use drop to get rid of dimensions which have only one level.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

matrix, Arithmetic, diag.

Examples

x <- 1:4
(z <- x %*% x)    # scalar ("inner") product (1 x 1 matrix)
drop(z)             # as scalar

y <- diag(x)
z <- matrix(1:12, ncol = 3, nrow = 4)
y %*% z
y %*% x
x %*% z


Matrices

Description

matrix creates a matrix from the given set of values.

as.matrix attempts to turn its argument into a matrix.

is.matrix tests if its argument is a (strict) matrix. It is generic: you can write methods to handle specific classes of objects, see InternalMethods.

Usage

matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE,
       dimnames = NULL)

as.matrix(x)

is.matrix(x)

Arguments

data | an optional data vector.
nrow | the desired number of rows
ncol | the desired number of columns
byrow | logical. If FALSE (the default) the matrix is filled by columns, otherwise the matrix is filled by rows.
dimnames | A dimnames attribute for the matrix: a list of length 2 giving the row and column names respectively.
x | an R object.

Details

If either of nrow or ncol is not given, an attempt is made to infer it from the length of data and the other parameter.

If there are too few elements in data to fill the array, then the elements in data are recycled. If data has length zero, NA of an appropriate type is used for atomic vectors (0 for raw vectors) and NULL for lists.

is.matrix returns TRUE if x is a matrix (i.e., it is not a data.frame and has a dim attribute of length 2) and FALSE otherwise.

as.matrix is a generic function. The method for data frames will convert any non-numeric/complex column into a character vector using format and so return a character matrix, except that all-logical data frames will be coerced to a logical matrix. When coercing a vector, it produces a one-column matrix, and promotes the names (if any) of the vector to the rownames of the matrix.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

data.matrix, which attempts to convert to a numeric matrix.

Examples

is.matrix(as.matrix(1:10))
!is.matrix(warpbreaks)# data.frame, NOT matrix!
warpbreaks[1:10,]
as.matrix(warpbreaks[1:10,]) #using as.matrix.data.frame(.) method

# Example of setting row and column names
mdat <- matrix(c(1,2,3, 11,12,13), nrow = 2, ncol=3, byrow=TRUE,
               dimnames = list(c("row1", "row2"), c("C.1", "C.2", "C.3")))
mdat


Find Maximum Position in Matrix

Description

Find the maximum position for each row of a matrix, breaking ties at random.

Usage

max.col(m, ties.method=c("random", "first", "last"))

Arguments

m | numerical matrix
ties.method | a character string specifying how “ties” are handled, "random" by default; can be abbreviated; see Details.

Details

When ties.method = "random", as per default, ties are broken at random. In this case, the determination of “tie” assumes that the entries are probabilities: there is a relative tolerance of 1e-5, relative to the largest entry in the row.

If ties.method = "first", max.col returns the column number of the first of several maxima in every row, the same as unname(apply(m, 1, which.max)).
Correspondingly, ties.method = "last" returns the last of possibly several indices.

Value

index of a maximal value for each row, an integer vector of length nrow(m).

References

Venables, W. N. and Ripley, B. D. (2002) Modern Applied Statistics with S. New York: Springer (4th ed).

See Also

which.max for vectors.

Examples

table(mc <- max.col(swiss))# mostly "1" and "5", 5 x "2" and once "4"
swiss[unique(print(mr <- max.col(t(swiss)))) , ] # 3 33 45 45 33 6

set.seed(1)# reproducible example:
(mm <- rbind(x = round(2*runif(12)),
             y = round(5*runif(12)),
             z = round(8*runif(12))))
## Not run:
  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
x    1    1    1    2    0    2    2    1    1     0     0     0
y    3    2    4    2    4    5    2    4    5     1     3     1
z    2    3    0    3    7    3    4    5    4     1     7     5
## End(Not run)
## column indices of all row maxima :
str(lapply(1:3, function(i) which(mm[i,] == max(mm[i,]))))
max.col(mm) ; max.col(mm) # "random"
max.col(mm, "first")# -> 4 6 5
max.col(mm, "last") # -> 7 9 11


Arithmetic Mean

Description

Generic function for the (trimmed) arithmetic mean.

Usage

mean(x, ...)

## Default S3 method:
mean(x, trim = 0, na.rm = FALSE, ...)

Arguments

x | An R object. Currently there are methods for numeric data frames, numeric vectors and dates. A complex vector is allowed for trim = 0, only.
trim | the fraction (0 to 0.5) of observations to be trimmed from each end of x before the mean is computed.
na.rm | a logical value indicating whether NA values should be stripped before the computation proceeds.
... | further arguments passed to or from other methods.

Value

For a data frame, a named vector with the appropriate method being applied column by column.
If trim is zero (the default), the arithmetic mean of the values in x is computed, as a numeric or complex vector of length one. If any argument is not logical (coerced to numeric), integer, numeric or complex, NA is returned, with a warning.
If trim is non-zero, a symmetrically trimmed mean is computed with a fraction of trim observations deleted from each end before the mean is computed.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

weighted.mean, mean.POSIXct

Examples

x <- c(0:10, 50)
xm <- mean(x)
c(xm, mean(x, trim = 0.10))

mean(USArrests, trim = 0.2)


Memory Available for Data Storage

Description

Use command line options to control the memory available for R.

Usage

Rgui --min-vsize=vl --max-vsize=vu --min-nsize=nl --max-nsize=nu --max-ppsize=N
Rterm --min-vsize=vl --max-vsize=vu --min-nsize=nl --max-nsize=nu --max-ppsize=N

mem.limits(nsize = NA, vsize = NA)

Arguments

vl, vu, vsize | Heap memory in bytes.
nl, nu, nsize | Number of cons cells.
N | Number of nested PROTECT calls.

.

Details

R has a variable-sized workspace. There is much less need to set memory options than prior to R 1.2.0, and most users will never need to set these. They are provided both as a way to control the overall memory usage (which can also be done using the option --max-mem-size on Windows), and since setting larger values of the minima will make R slightly more efficient on large tasks.

(On Windows the --max-mem-size option sets the maximum memory allocation: it has a minimum allowed value of 32M. This is intended to catch attempts to allocate excessive amounts of memory which may cause other processes to run out of resources. The default is the smaller of the amount of physical RAM in the machine and 1024Mb. See also memory.limit.)

To understand the options, one needs to know that R maintains separate areas for fixed and variable sized objects. The first of these is allocated as an array of “cons cells” (Lisp programmers will know what they are, others may think of them as the building blocks of the language itself, parse trees, etc.), and the second are thrown on a “heap” of “Vcells” of 8 bytes each. Effectively, the inputs vl and vu are rounded up to the next multiple of 8.

Each cons cell occupies 28 bytes on a 32-bit machine, (usually) 56 bytes on a 64-bit machine.

The --*-nsize options can be used to specify the number of cons cells and the --*-vsize options specify the size of the vector heap in bytes. Both options must be integers or integers followed by G, M, K, or k meaning Giga (2^{30} = 1073741824) Mega (2^{20} = 1048576), (computer) Kilo (2^{10} = 1024), or regular kilo (1000).

The --min-* options set the minimal sizes for the number of cons cells and for the vector heap. These values are also the initial values, but thereafter R will grow or shrink the areas depending on usage, but never exceeding the limits set by the --max-* options nor decreasing below the initial values.

The default values are currently minima of 350k cons cells, 6Mb of vector heap and no maxima (other than machine resources). The maxima can be changed during an R session by calling mem.limits. (If this is called with the default values, it reports the current settings.)

You can find out the current memory consumption (the heap and cons cells used as numbers and megabytes) by typing gc() at the R prompt. Note that following gcinfo(TRUE), automatic garbage collection always prints memory use statistics. Maxima will never be reduced below the current values for triggering garbage collection, and attempts to do so will be silently ignored.

The option --max-ppsize controls the maximum size of the pointer protection stack. This defaults to 50000, but can be increased to allow deep recursion or large and complicated calculations to be done. Note that parts of the garbage collection process goes through the full reserved pointer protection stack and hence becomes slower when the size is increased. Currently the maximum value accepted is 500000.

Value

mem.limits() returns an integer vector giving the current settings of the maxima, possibly NA.

See Also

An Introduction to R for more command-line options

Memory-limits for the design limitations.

gc for information on the garbage collector and total memory usage, object.size(a) for the (approximate) size of R object a. memory.profile for profiling the usage of cons cells.

memory.size to monitor total memory usage, memory.limit for the current limit.

Examples

# Start R with 10MB of heap memory and 500k cons cells, limit to
# 100Mb and 1M cells
## Not run:
## Unix
R --min-vsize=10M --max-vsize=100M --min-nsize=500k --max-nsize=1M
## End(Not run)


Memory Limits in R

Description

R holds objects it is using in memory. This help file documents the current design limitations on large objects: these differ between 32-bit and 64-bit builds of R.

Details

R holds all objects in memory, and there are limits based on the amount of memory that can be used by all objects:

  • There may be limits on the size of the heap and the number of cons cells allowed – see Memory – but these are usually not imposed.
  • There is a limit on the address space of a single process such as the R executable. This is 2Gb under 32-bit Windows unless the OS's default has been changed to allow more (up to 3Gb). See http://www.microsoft.com/whdc/system/platform/server/PAE/PAEmem.mspx. (R can be run under Win64 but the 2GB limit applies there and it cannot be increased to 3GB.)
  • Under Windows, R does impose limits on the total memory allocation available to a single run, as the OS provides no way to do so. See memory.size and memory.limit.

Error messages beginning cannot allocate vector of size indicate a failure to obtain memory, either because the size exceeded the address-space limit for a process or, more likely, because the system was unable to provide the memory. Note that on a 32-bit OS there may well be enough free memory available, but not a large enough contiguous block of address space into which to map it.

There are also limits on individual objects. On all versions of R, the maximum length (number of elements) of a vector is 2^31 - 1 ~ 2*10^9, as lengths are stored as signed integers. In addition, the storage space cannot exceed the address limit, and if you try to exceed that limit, the error message begins cannot allocate vector of length. The number of characters in a character string is in theory only limited by the address space.

See Also

object.size(a) for the (approximate) size of R object a.


Profile the Usage of Cons Cells

Description

Lists the usage of the cons cells by SEXPREC type.

Usage

memory.profile()

Details

The current types and their uses are listed in the include file ‘Rinternals.h’.

Value

A vector of counts, named by the types. See typeof for an explanation of types.

See Also

gc for the overall usage of cons cells.

Examples

memory.profile()


Merge Two Data Frames

Description

Merge two data frames by common columns or row names, or do other versions of database “join” operations.

Usage

merge(x, y, ...)

## Default S3 method:
merge(x, y, ...)

## S3 method for class 'data.frame':
merge(x, y, by = intersect(names(x), names(y)),
      by.x = by, by.y = by, all = FALSE, all.x = all, all.y = all,
      sort = TRUE, suffixes = c(".x",".y"), ...)

Arguments

x, y | data frames, or objects to be coerced to one.
by, by.x, by.y | specifications of the common columns. See Details.
all | logical; all = L is shorthand for all.x = L and all.y = L.
all.x | logical; if TRUE, then extra rows will be added to the output, one for each row in x that has no matching row in y. These rows will have NAs in those columns that are usually filled with values from y. The default is FALSE, so that only rows with data from both x and y are included in the output.
all.y | logical; analogous to all.x above.
sort | logical. Should the results be sorted on the by columns?
suffixes | character(2) specifying the suffixes to be used for making non-by names() unique.
... | arguments to be passed to or from methods.

Details

By default the data frames are merged on the columns with names they both have, but separate specifications of the columns can be given by by.x and by.y. Columns can be specified by name, number or by a logical vector: the name "row.names" or the number 0 specifies the row names. The rows in the two data frames that match on the specified columns are extracted, and joined together. If there is more than one match, all possible matches contribute one row each.

If by or both by.x and by.y are of length 0 (a length zero vector or NULL), the result, r, is the “Cartesian product” of x and y, i.e., dim(r) = c(nrow(x)*nrow(y), ncol(x) + ncol(y)).

If all.x is true, all the non matching cases of x are appended to the result as well, with NA filled in the corresponding columns of y; analogously for all.y.

If the remaining columns in the data frames have any common names, these have suffixes (".x" and ".y" by default) appended to make the names of the result unique.

Prior to R 2.4.0 the complexity was proportional to the product of the numbers of rows of x and y. As from R 2.4.0 it is proportional to the length of the answer, which can be much less if there are few matches (for example, only 1–1 matches).

Value

A data frame. The rows are by default lexicographically sorted on the common columns, but for sort=FALSE are in an unspecified order. The columns are the common columns followed by the remaining columns in x and then those in y. If the matching involved row names, an extra character column called Row.names is added at the left, and in all cases the result has no special row names.

See Also

data.frame, by, cbind

Examples

## use character columns of names to get sensible sort order
authors <- data.frame(
    surname = I(c("Tukey", "Venables", "Tierney", "Ripley", "McNeil")),
    nationality = c("US", "Australia", "US", "UK", "Australia"),
    deceased = c("yes", rep("no", 4)))
books <- data.frame(
    name = I(c("Tukey", "Venables", "Tierney",
             "Ripley", "Ripley", "McNeil", "R Core")),
    title = c("Exploratory Data Analysis",
              "Modern Applied Statistics ...",
              "LISP-STAT",
              "Spatial Statistics", "Stochastic Simulation",
              "Interactive Data Analysis",
              "An Introduction to R"),
    other.author = c(NA, "Ripley", NA, NA, NA, NA,
                     "Venables & Smith"))

(m1 <- merge(authors, books, by.x = "surname", by.y = "name"))
(m2 <- merge(books, authors, by.x = "name", by.y = "surname"))
stopifnot(as.character(m1[,1]) == as.character(m2[,1]),
          all.equal(m1[, -1], m2[, -1][ names(m1)[-1] ]),
          dim(merge(m1, m2, by = integer(0))) == c(36, 10))

## "R core" is missing from authors and appears only here :
merge(authors, books, by.x = "surname", by.y = "name", all = TRUE)


Diagnostic Messages

Description

Generate a diagnostic message from its arguments.

Usage

message(..., domain = NULL)
suppressMessages(expr)

Arguments

... | character vectors (which are pasted together with no separator), a condition object, or NULL.
domain | see gettext. If NA, messages will not be translated.
expr | expression to evaluate.

Details

message is used for generating “simple” diagnostic messages which are neither warnings nor errors, but nevertheless represented as conditions.

While the message is being processed, a muffleMessage restart is available.

suppressMessages evaluates its expression in a context that ignores all “simple” diagnostic messages.

See Also

warning and stop for generating warnings and errors; conditions for condition handling and recovery.

gettext for the mechanisms for the automated translation of text.

Examples

message("ABC", "DEF")
suppressMessages(message("ABC"))


Does a Formal Argument have a Value?

Description

missing can be used to test whether a value was specified as an argument to a function.

Usage

missing(x)

Arguments

x a formal argument.

Details

missing(x) is only reliable if x has not been altered since entering the function: in particular it will always be false after x <- match.arg(x).

The example shows how a plotting function can be written to work with either a pair of vectors giving x and y coordinates of points to be plotted or a single vector giving y values to be plotted against their indexes.

Currently missing can only be used in the immediate body of the function that defines the argument, not in the body of a nested function or a local call. This may change in the future.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language. Springer.

See Also

substitute for argument expression; NA for “missing values” in data.

Examples

myplot <- function(x,y) {
                if(missing(y)) {
                        y <- x
                        x <- 1:length(y)
                }
                plot(x,y)
        }


The (Storage) Mode of an Object

Description

Get or set the type or storage mode of an object.

Usage

mode(x)
mode(x) <- value
storage.mode(x)
storage.mode(x) <- value

Arguments

x | any R object.
value | a character string giving the desired (storage) mode of the object.

Details

Both mode and storage.mode return a character string giving the (storage) mode of the object — often the same — both relying on the output of typeof(x), see the example below.

The two replacement versions are currently identical. Both mode(x) <- "newmode" and storage.mode(x) <- "newmode" change the mode or storage.mode of object x to newmode. This is only supported if there is an appropriate as.newmode function, for example "logical", "integer", "double", "complex", "raw", "character", "list", "expression", "name", "symbol" and "function".

As storage mode "single" is only a pseudo-mode in R, it will not be reported by mode or storage.mode: use attr(object, "Csingle") to examine this. However, the replacement versions can be used to set the mode to "single", which sets the real mode to "double" and the "Csingle" attribute to TRUE. Setting any other mode will remove this attribute.

Note (in the examples below) that some calls have mode "(" which is S compatible.

Mode names

Modes have the same set of names as types (see typeof) except that

  • types "integer" and "double" are returned as "numeric".
  • types "special" and "builtin" are returned as "function".
  • type "symbol" is called mode "name".
  • type "language" is returned as "(" or "call".

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

typeof for the R-internal “mode”, attributes.

Examples

sapply(options(),mode)

cex3 <- c("NULL","1","1:1","1i","list(1)","data.frame(x=1)", "pairlist(pi)",
  "c", "lm", "formals(lm)[[1]]",  "formals(lm)[[2]]",
  "y~x","expression((1))[[1]]", "(y~x)[[1]]", "expression(x <- pi)[[1]][[1]]")
lex3 <- sapply(cex3, function(x) eval(parse(text=x)))
mex3 <- t(sapply(lex3, function(x) c(typeof(x), storage.mode(x), mode(x))))
dimnames(mex3) <- list(cex3, c("typeof(.)","storage.mode(.)","mode(.)"))
mex3

## This also makes a local copy of 'pi':
storage.mode(pi) <- "complex"
storage.mode(pi)
rm(pi)


Not Available / “Missing” Values

Description

NA is a logical constant of length 1 which contains a missing value indicator. NA can be freely coerced to any other vector type except raw.

The generic function is.na indicates which elements are missing.

The generic function is.na<- sets elements to NA.

Usage

NA
is.na(x)
## S3 method for class 'data.frame':
is.na(x)

is.na(x) <- value

Arguments

x | an R object to be tested.
value | a suitable index vector for use with x.

Details

The NA of character type is distinct from the string "NA". Programmers who need to specify an explicit string NA should use as.character(NA) rather than "NA", or set elements to NA using is.na<-.

is.na(x) works elementwise when x is a list. It is generic: you can write methods to handle specific classes of objects, see InternalMethods.

Function is.na<- may provide a safer way to set missingness. It behaves differently for factors, for example.

Value

The default method for is.na returns a logical vector of the same “form” as its argument x, containing TRUE for those elements marked NA or NaN (!) and FALSE otherwise. dim, dimnames and names attributes are preserved.
The method is.na.data.frame returns a logical matrix with the same dimensions as the data frame, and with dimnames taken from the row and column names of the data frame.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language. Springer.

See Also

NaN, is.nan, etc., and the utility function complete.cases.

na.action, na.omit, na.fail on how methods can be tuned to deal with missing values.

Examples

is.na(c(1, NA))        #> FALSE  TRUE
is.na(paste(c(1, NA))) #> FALSE FALSE

(xx <- c(0:4))
is.na(xx) <- c(2, 4)
xx                     #> 0 NA  2 NA  4


Names and Symbols

Description

as.symbol coerces its argument to be a symbol, or equivalently, a name. The argument must be of mode "character". as.name is an alias for as.symbol.

is.symbol (and is.name equivalently) returns TRUE or FALSE depending on whether its argument is a symbol (i.e., name) or not.

Usage

as.symbol(x)
is.symbol(y)

as.name(x)
is.name(y)

Arguments

x, y objects to be coerced or tested.

Details

is.symbol is generic: you can write methods to handle specific classes of objects, see InternalMethods.

Note

The term “symbol” is from the LISP background of R, whereas “name” has been the standard S term for this.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

call, is.language. For the internal object mode, typeof.

Examples

an <- as.name("arrg")
is.name(an) # TRUE
mode(an)   # name
typeof(an) # symbol


The Names of an Object

Description

Functions to get or set the names of an object.

Usage

names(x)
names(x) <- value

Arguments

x | an R object.
value | a character vector of up to the same length as x, or NULL.

Details

names is a generic accessor function, and names<- is a generic replacement function. The default methods get and set the "names" attribute of a vector (including a list) or pairlist.

If value is shorter than x, it is extended by character NAs to the length of x.

It is possible to update just part of the names attribute via the general rules: see the examples. This works because the expression there is evaluated as z <- "names<-"(z, "[<-"(names(z), 3, "c2")).

The name "" is special: it is used to indicate that there is no name associated with an element of a (atomic or generic) vector. Subscripting by "" will match nothing (not even elements which have no name).

A name can be character NA, but such a name will never be matched and is likely to lead to confusion.

Value

For names, NULL or a character vector of the same length as x. (NULL is given if the object has no names, including for objects of types which cannot have names.)
For names<-, the updated object. (Note that the value of names(x) <- value is that of the assignment, value, not the return value from the left-hand side.)

Note

For vectors, the names are one of the attributes with restrictions on the possible values. For pairlists, the names are the tags and converted to and from a character vector.

For a one-dimensional array the names attribute really is dimnames[[1]].

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Examples

# print the names attribute of the islands data set
names(islands)

# remove the names attribute
names(islands) <- NULL
islands
rm(islands) # remove the copy made

z <- list(a=1, b="c", c=1:3)
names(z)
# change just the name of the third element.
names(z)[3] <- "c2"
z

z <- 1:3
names(z)
## assign just one name
names(z)[2] <- "b"
z


The Number of Arguments to a Function

Description

When used inside a function body, nargs returns the number of arguments supplied to that function, including positional arguments left blank.

Usage

nargs()

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

args, formals and sys.call.

Examples

tst <- function(a, b = 3, ...) {nargs()}
tst() # 0
tst(clicketyclack) # 1 (even non-existing)
tst(c1, a2, rr3) # 3

foo <- function(x, y, z, w) {
   cat("call was", deparse(match.call()), "\n")
   nargs()
}
foo()    # 0
foo(,,3) # 3
foo(z=3) # 1, even though this is the same call

nargs()# not really meaningful


Count the Number of Characters (Bytes)

Description

nchar takes a character vector as an argument and returns a vector whose elements contain the sizes of the corresponding elements of x.

Usage

nchar(x, type = "bytes")

Arguments

x | character vector, or a vector to be coerced to a character vector.
type | character string: partial matching to one of c("bytes", "chars", "width"). See Details.

Details

The ‘size’ of a character string can be measured in one of three ways

bytes
The number of bytes needed to store the string (plus in C a final terminator which is not counted).
chars
The number of human-readable characters.
width
The number of columns cat will use to print the string in a monospaced font. The same as chars if this cannot be calculated.

These will often be the same, and almost always will be in single-byte locales. There will be differences between the first two with multibyte character sequences, e.g. in UTF-8 locales. If the byte stream contains embedded nul bytes, type = "bytes" looks at all the bytes whereas the other two types look only at the string as printed by cat, up to the first nul byte.

The internal equivalent of the default method of as.character is performed on x (so there is no method dispatch). If you want to operate on non-vector objects passing them through deparse first will be required.

Value

An integer vector giving the sizes of each element, currently always 2 for missing values (for NA).
If an element is invalid in a multi-byte character set such as UTF-8, its number of characters and the width will be NA. Otherwise the number of characters will be non-negative, so !is.na(nchar(x, "chars")) is a test of validity.
Names, dims and dimnames are copied from the input.

Note

This does not by default give the number of characters that will be used to print() the string. Use encodeString to find the characters used to print the string.

Embedded nul bytes are included in the byte count (but not the final nul).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

strwidth giving width of strings for plotting; paste, substr, strsplit

Examples

x <- c("asfef","qwerty","yuiop[","b","stuff.blah.yech")
nchar(x)
# 5  6  6  1 15

nchar(deparse(mean))
# 18 17


The Number of Levels of a Factor

Description

Return the number of levels which its argument has.

Usage

nlevels(x)

Arguments

x an object, usually a factor.

Details

If the argument is not a factor, NA is returned.

The actual factor levels (if they exist) can be obtained with the levels function.

Examples

nlevels(gl(3,7)) # = 3


Class for “no quote” Printing of Character Strings

Description

Print character strings without quotes.

Usage

noquote(obj)

## S3 method for class 'noquote':
print(x, ...)

## S3 method for class 'noquote':
c(..., recursive = FALSE)

Arguments

obj | any R object, typically a vector of character strings.
x | an object of class "noquote".
... | further options passed to next methods, such as print.
recursive | for compatibility with the generic c function.

Details

noquote returns its argument as an object of class "noquote". There is a method for c() and subscript method ("[.noquote") which ensures that the class is not lost by subsetting. The print method (print.noquote) prints character strings without quotes ("...").

These functions exist both as utilities and as an example of using (S3) class and object orientation.

Author(s)

Martin Maechler maechler@stat.math.ethz.ch

See Also

methods, class, print.

Examples

letters
nql <- noquote(letters)
nql
nql[1:4] <- "oh"
nql[1:12]

cmp.logical <- function(log.v)
{
  ## Purpose: compact printing of logicals
  log.v <- as.logical(log.v)
  noquote(if(length(log.v)==0)"()" else c(".","|")[1+log.v])
}
cmp.logical(runif(20) > 0.8)


Not Yet Implemented Functions and Unused Arguments

Description

In order to pinpoint missing functionality, the R core team uses these functions for missing R functions and not yet used arguments of existing R functions (which are typically there for compatibility purposes).

You are very welcome to contribute your code ...

Usage

.NotYetImplemented()
.NotYetUsed(arg, error = TRUE)

Arguments

arg | an argument of a function that is not yet used.
error | a logical. If TRUE, an error is signalled; if FALSE; only a warning is given.

See Also

the contrary, Deprecated and Defunct for outdated code.

Examples

require(graphics)
require(stats)
plot.mlm         # to see how the "NotYetImplemented"
                 # reference is made automagically
try(plot.mlm())

barplot(1:5, inside = TRUE) # 'inside' is not yet used


The Number of Rows/Columns of an Array

Description

nrow and ncol return the number of rows or columns present in x. NCOL and NROW do the same treating a vector as 1-column matrix.

Usage

nrow(x)
ncol(x)
NCOL(x)
NROW(x)

Arguments

x a vector, array or data frame

Value

an integer of length 1 or NULL.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole (ncol and nrow.)

See Also

dim which returns all dimensions; array, matrix.

Examples

ma <- matrix(1:12, 3, 4)
nrow(ma)   # 3
ncol(ma)   # 4

ncol(array(1:24, dim = 2:4)) # 3, the second dimension
NCOL(1:12) # 1
NROW(1:12) # 12


Experimental Alternative Name Specification Support

Description

Alternative interface for specifying a name space within the code of a package.

Usage

.Export(...)
.Import(...)
.ImportFrom(name, ...)
.S3method(generic, class, method)

Arguments

... | name or literal character string arguments.
name | name or literal character string.
generic | name or literal character string.
class | name or literal character string.
method | optional character or function argument.

Details

As an experimental alternative to using a ‘NAMESPACE’ file it is possible to add a name space to a package by adding a Namespace: <package_name> entry to the ‘DESCRIPTION’ file and placing directives to specify imports and exports directly in package code. These directives should be viewed as declarations, not as function calls. Except to the optional method argument to .S3method arguments are not evaluated. These directives should only be used at top level of package code except as noted below.

.Export is used to declare exports. Its arguments should be literal names or character strings. .Export should only be used at package top level.

.Import is used to declare the import of entire name spaces. Its arguments should be literal names or character strings. .ImportFrom is used to declare the import of selected variables from a single name space. The first argument is a literal name or character string identifying the source name space; the remaining arguments are literal names or character strings identifying the variables to import. As an experimental feature both .Import and .ImportFrom can be used to import variables into a local environment. The drawback of allowing this is that dependencies cannot be determined easily at package load time, and as a result this feature may need to be dropped.

.S3method is used to declare a method for S3-style UseMethod dispatch. This is needed since methods in packages that are imported but not on the search path might not be visible to the standard dispatch mechanism at a call site. The first argument is the name of the generic, the second specifies the class. The third argument is optional and defaults to the usual concatenation of generic and class separated by a period. If supplied, the third argument should evaluate to a character string or a function. If the third argument is omitted or a character string is supplied, then a function by that name must be defined. If a function is supplied, it is used as the method. When the method is specified as a name, explicitly or implicitly, the function lookup is handled lazily; this allows the definition to occur after the .S3method declaration and also integrates with possible data base storage of package code.

Author(s)

Luke Tierney

Examples

## Not run:
## code for package/name space 'foo'
x <- 1
f <- function(y) c(x,y)
print.foo <- function(x, ...) cat("<a foo>\n")
.Export(f)
S3method(print,foo)

## code for package/name space 'bar'
.Import(foo)
c <- function(...) sum(...)
g <- function(y) f(c(y, 7))
h <- function(y) y+9
.Export(g, h)
## End(Not run)


Double Colon and Triple Colon Operators

Description

Accessing exported and internal variables in a name space.

Usage

pkg::name
pkg:::name

Arguments

pkg | package name symbol or literal character string.
name | variable name symbol or literal character string.

Details

The expression pkg::name returns the value of the exported variable name in package pkg if the package has a name space. The expression pkg:::name returns the value of the internal variable name in package pkg if the package has a name space. The package will be loaded if it was not loaded already before the call. Assignment into name spaces is not supported.

If the package pkg does not have a name space but is on the search path then pkg::name returns the value of name in the package environent.

See Also

get to access an object masked by another of the same name.

Examples

base::log
base::"+"


Hooks for Name Space events

Description

Packages with name spaces can supply functions to be called when loaded, attached or unloaded.

Usage

.onLoad(libname, pkgname)
.onAttach(libname, pkgname)
.onUnload(libpath)

Arguments

libname | a character string giving the library directory where the package defining the namespace was found.
pkgname | a character string giving the name of the package, including the version number if the package was installed with --with-package-versions.
libpath | a character string giving the complete path to the package.

Details

These functions apply only to packages with name spaces.

After loading, loadNamespace looks for a hook function named .onLoad and runs it before sealing the namespace and processing exports.

If a name space is unloaded (via unloadNamespace), a hook function .onUnload is run before final unloading.

Note that the code in .onLoad and .onUnload is run without the package being on the search path, but (unless circumvented) lexical scope will make objects in the namespace and its imports visible. (Do not use the double colon operator in .onLoad as exports have not been processed at the point it is run.)

When the package is attached (via library), the hook function .onAttach is looked for and if found is called after the exported functions are attached and before the package environment is sealed. This is less likely to be useful than .onLoad, which should be seen as the analogue of .First.lib (which is only used for packages without a name space).

.onLoad, .onUnload and .onAttach are looked for as internal variables in the name space and should not be exported.

If a function .Last.lib is visible in the package, it will be called when the package is detached: this does need to be exported.

Anything needed for the functioning of the name space should be handled at load/unload times by the .onLoad and .onUnload hooks. For example, shared libraries can be loaded (unless done by a useDynLib directive in the ‘NAMESPACE’ file) and initialized in .onLoad and unloaded in .onUnload. Use .onAttach only for actions that are needed only when the package becomes visible to the user, for example a start-up message.

If a package was installed with --with-package-versions, the pkgname supplied will be something like tree_1.0-16.

See Also

setHook shows how users can set hooks on the same events.


Name Space Internals

Description

Internal name space support functions. Not intended to be called directly.

Usage

asNamespace(ns, base.OK = TRUE)
getNamespaceInfo(ns, which)
importIntoEnv(impenv, impnames, expenv, expnames)
isBaseNamespace(ns)
namespaceExport(ns, vars)
namespaceImport(self, ...)
namespaceImportFrom(self, ns, vars, generics, packages)
namespaceImportClasses(self, ns, vars)
namespaceImportMethods(self, ns, vars)
packageHasNamespace(package, package.lib)
parseNamespaceFile(package, package.lib, mustExist = TRUE)
registerS3method(genname, class, method, envir = parent.frame())
registerS3methods(info, package, env)
setNamespaceInfo(ns, which, val)
.mergeExportMethods(new, ns)
.mergeImportMethods(impenv, expenv, metaname)
.knownS3Generics

Arguments

ns | string or name space environment.
base.OK | logical.
impenv | environment.
expenv | name space environment.
vars | character vector.
generics | optional character vector.
self | name space environment.
package | string naming the package/name space to load.
packages | vector of package names parallel to generics.
package.lib | character vector specifying library.
mustExist | logical.
genname | character.
class | character.
envir, env | environment.
info | a 3-column character matrix.
which | character.
val | any object.
... | character arguments.
metaname | the methods table name.

Details

packageHasNamespace does not indicate if the package has a namespace, rather if it has a ‘NAMESPACE’ file, which base does not. But then you are not intended to be using it ....

Author(s)

Luke Tierney


Loading and Unloading Name Spaces

Description

Functions to load and unload namespaces.

Usage

attachNamespace(ns, pos = 2, dataPath = NULL)
loadNamespace(package, lib.loc = NULL,
              keep.source = getOption("keep.source.pkgs"),
              partial = FALSE, declarativeOnly = FALSE)
loadedNamespaces()
unloadNamespace(ns)

Arguments

ns | string or namespace object.
pos | integer specifying position to attach.
dataPath | path to directory containing a database of datasets to be lazy-loaded into the attached environment.
package | string naming the package/name space to load.
lib.loc | character vector specifying library search path.
keep.source | logical specifying whether to retain source. This applies only to the specified name space, and not to other name spaces which might be loaded to satisfy imports. For more details see this argument to library.
partial | logical; if true, stop just after loading code.
declarativeOnly | logical; disables .Import, etc, if true.

Details

The functions loadNamespace and attachNamespace are usually called implicitly when library is used to load a name space and any imports needed. However it may be useful to call these functions directly at times.

loadNamespace loads the specified name space and registers it in an internal data base. A request to load a name space that is already loaded has no effect. The arguments have the same meaning as the corresponding arguments to library, whose help page explains the details of how a particular installed package comes to be chosen. After loading, loadNamespace looks for a hook function named .onLoad as an internal variable in the name space (it should not be exported). This function is called with the same arguments as .First.lib. Partial loading is used to support installation with the --save and --lazy options.

loadNamespace does not attach the name space it loads to the search path. attachNamespace can be used to attach a frame containing the exported values of a name space to the search path. The hook function .onAttach is run after the name space exports are attached.

loadedNamespaces returns a character vector of the names of the loaded name spaces.

unloadNamespace can be used to force a name space to be unloaded. An error is signaled if the name space is imported by other loaded name spaces. If defined, a hook function .onUnload is run before removing the name space from the internal registry. unloadNamespace will first detach a package of the same name if one is on the path, thereby running a .Last.lib function in the package if one is exported.

Author(s)

Luke Tierney


Low Level Name Space Support Functions

Description

Low level name space support functions.

Usage

loadingNamespaceInfo()
saveNamespaceImage(package, rdafile, lib.loc = NULL,
                   keep.source = getOption("keep.source.pkgs"),
                   compress = TRUE)

Arguments

package | string naming the package/name space to load.
rdafile | name of file to save to.
lib.loc | character vector specifying library search path.
keep.source | logical specifying whether to retain source.
compress | option passed to save.

Details

The functions loadNamespace and attachNamespace are usually called implicitly when library is used to load a name space and any imports needed. However it may be useful to call these functions directly at times.

loadNamespace loads the specified name space and registers it in an internal data base. A request to load a name space that is already loaded has no effect. The arguments have the same meaning as the corresponding arguments to library. After loading, loadNamespace looks for a hook function named .onLoad as an internal variable in the name space (it should not be exported). This function is called with the same arguments as .First.lib. Partial loading is used to support installation with the --save option.

loadNamespace does not attach the name space it loads to the search path. attachNamespace can be used to attach a frame containing the exported values of a name space to the search path. The hook function .onAttach is run after the name space exports are attached.

loadedNamespaces returns a character vector of the names of the loaded name spaces.

unloadNamespace can be used to force a name space to be unloaded. An error is signaled if the name space is imported by other loaded name spaces. If defined, a hook function .onUnload is run before removing the name space from the internal registry. unloadNamespace will first detach a package of the same name if one is on the path, thereby running a .Last.lib function in the package if one is exported.

loadingNamespaceInfo returns a list of the arguments that would be passed to .onLoad when a name space is being loaded. An error is signaled of a name space is not currently being loaded.

saveNamespaceImage is used to save name space images for packages installed with --save.

Author(s)

Luke Tierney


Name Space Reflection Support

Description

Functions to support reflection on name space objects.

Usage

getExportedValue(ns, name)
getNamespace(name)
getNamespaceExports(ns)
getNamespaceImports(ns)
getNamespaceName(ns)
getNamespaceUsers(ns)
getNamespaceVersion(ns)

Arguments

ns | string or name space object.
name | string or name.

Details

getExportedValue returns the value of the exported variable name in name space ns.

getNamespace returns the environment representing the name space name. The name space is loaded if necessary.

getNamespaceExports returns a character vector of the names exported by ns.

getNamespaceImports returns a representation of the imports used by name space ns. This representation is experimental and subject to change.

getNamespaceName and getNamespaceVersion return the name and version of the name space ns.

getNamespaceUsers returns a character vector of the names of the name spaces that import name space ns.

Author(s)

Luke Tierney


Top Level Environment

Description

Finding the top level environment.

Usage

topenv(envir = parent.frame(),
       matchThisEnv = getOption("topLevelEnvironment"))

Arguments

envir | environment.
matchThisEnv | return this environment, if it matches before any other criterion is satisfied. The default, the option “topLevelEnvironment”, is set by sys.source, which treats a specific environment as the top level environment. Supplying the argument as NULL means it will never match.

Details

topenv returns the first top level environment found when searching envir and its parent environments. An environment is considered top level if it is the internal environment of a name space, a package environment in the search path, or .GlobalEnv.

Examples

topenv(.GlobalEnv)
topenv(new.env())


The Null Object

Description

NULL represents the null object in R. NULL is used mainly to represent the lists with zero length, and is often returned by expressions and functions whose value is undefined.

as.null ignores its argument and returns the value NULL.

is.null returns TRUE if its argument is NULL and FALSE otherwise.

Usage

NULL
as.null(x, ...)
is.null(x)

Arguments

x | an object to be tested or coerced.
... | ignored.

Details

is.null is generic: you can write methods to handle specific classes of objects, see InternalMethods.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Examples

is.null(list())    # FALSE (on purpose!)
is.null(integer(0))# F
is.null(logical(0))# F
as.null(list(a=1,b='c'))


Numeric Vectors

Description

Creates or tests for objects of type "numeric".

Usage

numeric(length = 0)
as.numeric(x, ...)
is.numeric(x)

Arguments

length | desired length.
x | object to be coerced or tested.
... | further arguments passed to or from other methods.

Details

as.numeric is a generic function, but methods must be written for as.double, which it calls.

is.numeric is generic: you can write methods to handle specific classes of objects, see InternalMethods.
Note that is.numeric() returns FALSE for a factor via its "factor" method.

Value

numeric creates a real vector of the specified length. The elements of the vector are all equal to 0.
as.numeric attempts to coerce its argument to a numeric type (either "integer" or "double"). as.numeric for factors yields the codes underlying the factor levels, not the numeric representation of the labels, see also factor.
is.numeric returns TRUE if its argument is of mode "numeric" (type "double" or type "integer") and not a factor, and FALSE otherwise.

Note

R has no single precision data type. All real numbers are stored in double precision format.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Examples

as.numeric(c("-.1"," 2.7 ","B")) # (-0.1, 2.7, NA)  +  warning
as.numeric(factor(5:10))


Numeric Constants

Description

How R parses numeric constants.

Details

R parses numeric constants in its input in a very similar way to C floating-point constants.

Inf and NaN are numeric constants. All other numeric constants start with a digit or period.

Hexadecimal constants start with 0x or 0X followed by a non-empty sequence from 0-9 a-f A-F which is interpreted as a hexadecimal number.

Decimal constants consists of a nonempty sequence of digits possibly containing a period (the decimal point), optionally followed by a decimal exponent. A decimal exponent consists of an E or e followed by an optional plus or minus sign followed by a non-empty sequence of digits, and indicates multiplication by a power of ten.

A numeric constant immediately followed by i is regarded as an imaginary complex number.

Only the ASCII digits 0–9 are recognized as digits, even in languages which have other representations of digits. The ‘decimal separator’ is always a period and never a comma.

Note that a leading plus or minus is not part of numeric constant but a unary operator applied to the constant.

See Also

Syntax.

Quotes for the parsing of character constants,


Display Numbers in Octal

Description

Convert or print integers in octal format, with as many digits as are needed to display the largest, using leading zeroes as necessary.

Usage

## S3 method for class 'octmode':
as.character(x, ...)

## S3 method for class 'octmode':
format(x, ...)

## S3 method for class 'octmode':
print(x, ...)

Arguments

x | An object inheriting from class "octmode".
... | further arguments passed to or from other methods.

Details

Class "octmode" consists of integer vectors with that class attribute, used merely to ensure that they are printed in octal notation, specifically for Unix-like file permissions such as 755. Subsetting ([) works too.

See Also

These are auxiliary functions for file.info.

hexmode

Examples

(on <- structure(c(16,32, 127:129),  class = "octmode")) #-> print.*()
##-> "020" "040" "177" "200" "201"
unclass(on[3:4]) # subsetting


Function Exit Code

Description

on.exit records the expression given as its argument as needing to be executed when the current function exits (either naturally or as the result of an error). This is useful for resetting graphical parameters or performing other cleanup actions.

If no expression is provided, i.e., the call is on.exit(), then the current on.exit code is removed.

on.exit is a primitive function so positional matching is used and names of supplied arguments are ignored.

Usage

on.exit(expr, add = FALSE)

Arguments

expr | an expression to be executed.
add | if TRUE, add expr to be executed after any previously set expressions; otherwise (the default) expr will overwrite any previously set expressions.

Value

Invisible NULL.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

sys.on.exit which returns the expression stored for use by on.exit() in the function in which sys.on.exit() is evaluated.

Examples

opar <- par(mai = c(1,1,1,1))
on.exit(par(opar))


Operators on the Date Class

Description

Operators for the "Date" class.

There is an Ops method and specific methods for + and - for the Date class.

Usage

date + x
date - x
date1 lop date2

Arguments

date | date objects
date1, date2 | date objects or character vectors. (Character vectors are converted by as.Date.
x | a numeric vector (in days) or an object of class "difftime".
lop | One of ==, !=, <, <=, > or >=.

Examples

(z <- Sys.Date())
z + 10
z < c("2006-06-01", "2007-01-01", "2010-01-01")


Options Settings

Description

Allow the user to set and examine a variety of global “options” which affect the way in which R computes and displays its results.

Usage

options(...)

getOption(x)

.Options

Arguments

... | any options can be defined, using name = value or by passing a list of such tagged values. However, only the ones below are used in “base R”. Further, options('name') == options()['name'], see the example.
x | a character string holding an option name.

Details

Invoking options() with no arguments returns a list with the current values of the options. Note that not all options listed below are set initially. To access the value of a single option, one should use getOption("width"), e.g., rather than options("width") which is a list of length one.

.Options also always contains the options() list (as a pairlist, unsorted), for S compatibility. Assigning to it will make a local copy and not change the original.

Value

For getOption, the current value set for option x, or NULL if the option is unset.
For options(), a list of all set options sorted by name. For options(name), a list of length one containing the set value, or NULL if it is unset. For uses setting one or more options, a list with the previous values of the options changed (returned invisibly).

Options used in base R

add.smooth:
typically logical, defaulting to TRUE. Could also be set to an integer for specifying how many (simulated) smooths should be added. This is currently only used by plot.lm.
check.bounds:
logical, defaulting to FALSE. If true, a warning is produced whenever a “generalized vector” (atomic or list) is extended, by something like x <- 1:3; x[5] <- 6.
continue:
a non-empty string setting the prompt used for lines which continue over one line.
defaultPackages:
the packages that are attached by default when R starts up. Initially set from value of the environment variable R_DEFAULT_PACKAGES, or if that is unset to c("datasets", "utils", "grDevices", "graphics", "stats", "methods"). (Set R_DEFAULT_PACKAGES to NULL or a comma-separated list of package names.) A call to options should be in your ‘.Rprofile’ file to ensure that the change takes effect before the base package is initialized (see Startup).
deparse.max.lines:
controls the number of lines used when deparsing in traceback and browser. Initially unset, and only used if set to a positive integer.
digits:
controls the number of digits to print when printing numeric values. It is a suggestion only. Valid values are 1...22 with default 7. See print.default.
digits.secs:
controls the maximum number of digits to print when formatting time values in seconds. Valid values are 0...6 with default 0. See strftime.
download.file.method:
Method to be used for download.file. Currently download methods "internal", "wget" and "lynx" are available. There is no default for this option, when method = "auto" is chosen: see download.file.
echo:
logical. Only used in non-interactive mode, when it controls whether input is echoed. Command-line option --slave sets this initially to FALSE.
encoding:
The name of an encoding, default "native.enc"). See connections.
error:
either a function or an expression governing the handling of non-catastrophic errors such as those generated by stop as well as by signals and internally detected errors. If the option is a function, a call to that function, with no arguments, is generated as the expression. The default value is NULL: see stop for the behaviour in that case. The functions dump.frames and recover provide alternatives that allow post-mortem debugging.
expressions:
sets a limit on the number of nested expressions that will be evaluated. Valid values are 25...500000 with default 5000. If you increase it, you may also want to start R with a larger protection stack; see --max-ppsize in Memory. Note too that you may cause a segfault from overflow of the C stack, and on OSes where it is possible you may want to increase that.
keep.source:
When TRUE, the source code for functions (newly defined or loaded) is stored in their "source" attribute (see attr) allowing comments to be kept in the right places.

The default is interactive(), i.e., TRUE for interactive use.

keep.source.pkgs:
As for keep.source, for functions in packages loaded by library or require. Defaults to FALSE unless the environment variable R_KEEP_PKG_SOURCE is set to yes.

Note this does not apply to packages using lazy-loading or saved images. Whether they have kept source is determined when they are installed (and is almost certainly false).

mailer:
default mailer used by bug.report(). Can be "none".
max.contour.segments:
positive integer, defaulting to 250000 and usually not set. A limit on the number of segments in a single contour line in contour or contourLines.
max.print:
integer, defaulting to 99999. print or show methods can make use of this option, to limit the amount of information that is printed, to something in the order of (and typically slightly less than) max.print entries.
OutDec:
one-character string. The character to be used as the decimal point in output conversions, that is in printing, plotting and as.character but not deparsing.
pager:
the (stand-alone) program used for displaying text files on R's console, also used by file.show and sometimes help. Defaults to "internal", which uses a pager similar to the GUI console. Another possibility is "console" to use the console itself.
papersize:
the default paper format used by postscript; set by environment variable R_PAPERSIZE when R is started: if that is unset or invalid it defaults to "a4", or "letter" in US and Canadian locales.
printcmd:
the command used by postscript for printing; set by environment variable R_PRINTCMD when R is started. This should be a command that expects either input to be piped to ‘stdin’ or to be given a single filename argument.
prompt:
a non-empty string to be used for R's prompt; should usually end in a blank (" ").
save.defaults, save.image.defaults:
see save.
scipen:
integer. A penalty to be applied when deciding to print numeric values in fixed or exponential notation. Positive values bias towards fixed and negative towards scientific notation: fixed notation will be preferred unless it is more than scipen digits wider.
show.error.messages:
a logical. Should error messages be printed? Intended for use with try or a user-installed error handler.
stringsAsFactors:
The default setting for arguments of data.frame and read.table.
texi2dvi:
used by the unexported function texi2dvi in namespace tools.
timeout:
integer. The timeout for some Internet operations, in seconds. Default 60 seconds. See download.file and connections.
topLevelEnvironment:
see topenv and sys.source.
verbose:
logical. Should R report extra information on progress? Set to TRUE by the command-line option --verbose.
warn:
sets the handling of warning messages. If warn is negative all warnings are ignored. If warn is zero (the default) warnings are stored until the top–level function returns. If fewer than 10 warnings were signalled they will be printed otherwise a message saying how many (max 50) were signalled. An object called last.warning is created and can be printed through the function warnings. If warn is one, warnings are printed as they occur. If warn is two or larger all warnings are turned into errors.
warning.expression:
an R code expression to be called if a warning is generated, replacing the standard message. If non-null it is called irrespective of the value of option warn.
warnings.length:
sets the truncation limit for error and warning messages. A non-negative integer, with allowed values 100...8192, default 1000.
width:
controls the number of characters on a line. You may want to change this if you re-size the window that R is running in. Valid values are 10...10000 with default normally 80. (The limits on valid values are in file ‘Print.h’ and can be changed by re-compiling R.)

The ‘factory-fresh’ default settings of some of these options are
add.smooth | TRUE
check.bounds | FALSE
continue | "+ "
digits | 7
echo | TRUE
encoding | "native.enc"
error | NULL
expressions | 5000
keep.source | interactive()
keep.source.pkgs | FALSE
max.print | 99999
OutDec | "."
prompt | "> "
scipen | 0
show.error.messages | TRUE
timeout | 60
verbose | FALSE
warn | 0
warnings.length | 1000
width | 80

Others are set from environment variables or are platform-dependent.

Options set in package grDevices

These will be set when package grDevices (or its name space) is loaded if not already set.

device:
a character string giving the default device for that session. This defaults to the normal screen device (e.g., x11, windows or quartz) for an interactive session, and postscript in batch use or if a screen is not available.
locatorBell:
logical. Should selection in locator and identify be confirmed by a bell. Default TRUE. Honoured at least on X11 and windows devices.
par.ask.default:
logical. The default for par("ask") when a device is opened.
gamma:
double. The default value of gamma for windows devices, defaulting to 1 if unset (the default).
graphics.record:
logical. The default value of record for windows devices. Default FALSE.
windowsBuffered:
logical. Should windows devices be double-buffered?. Default TRUE.
windowsTimeout:
integer vector of length 2 representing two times in milliseconds. These control the double-buffering of windows devices when that is enabled: the first is the delay after plotting finishes (default 100) and the second is the update interval during continuous plotting (default 500).
xpinch, ypinch:
double. Pixels per inch, horizontally and vertically. If unset (the default), taken from Windows.

Options set in package stats

These will be set when package stats (or its name space) is loaded if not already set.

contrasts:
the default contrasts used in model fitting such as with aov or lm. A character vector of length two, the first giving the function to be used with unordered factors and the second the function to be used with ordered factors. By default the elements are named c("unordered", "ordered"), but the names are unused.
na.action:
the name of a function for treating missing values (NA's) for certain situations.
show.coef.Pvalues:
logical, affecting whether P values are printed in summary tables of coefficients. See printCoefmat.
show.signif.stars:
logical, should stars be printed on summary tables of coefficients? See printCoefmat.
ts.eps:
the relative tolerance for certain time series (ts) computations. Default 1e-05.
ts.S.compat:
logical. Used to select S compatibility for plotting time-series spectra. See the description of argument log in plot.spec.

Options set in package utils

These will be set when package utils (or its name space) is loaded if not already set.

browser:
default HTML browser used by help.start() on UNIX, or a non-default browser on Windows.
de.cellwidth:
integer: the cell widths (number of characters) to be used in the data editor dataentry. If this is unset (the default), 0, negative or NA, variable cell widths are used.
editor:
a non-empty string. Sets the default text editor, e.g., for edit. Set from the environment variable VISUAL on UNIX.
example.ask:
default for the ask argument of example.
help.try.all.packages:
default for an argument of help.
HTTPUserAgent:
string used as the user agent in HTTP requests. If NULL, HTTP requests will be made without a user agent header. The default is R (<version> <platform> <arch> <os>)
internet.info:
The minimum level of information to be printed on URL downloads etc. Default is 2, for failure causes. Set to 1 or 0 to get more information.
menu.graphics:
Logical: should graphical menus be used if available?. Defaults to TRUE. Currently applies to chooseCRANmirror, setRepositories and to select from multiple help files in help.
pkgType:
The default type of packages to be downloaded and installed – see install.packages. Possible values are "win.binary" (the default) and "source".
repos:
URLs of the repositories for use by update.packages. Defaults to c(CRAN="@CRAN@"), a value that causes some utilities to prompt for a CRAN mirror. To avoid this do set the CRAN mirror, by something like local({r <- getOption("repos"); r["CRAN"] <- "http://my.local.cran"; options(repos=r)}).

Note that you can add more repositories (Bioconductor and Omegahat, notably) using setRepositories().

SweaveHooks, SweaveSyntax:
see Sweave.
unzip:
the command used for unzipping help files. Defaults to "internal" when the internal unzip code is used.

Options used on Windows only

warn.FPU:
logical, by default undefined. If true, a warning is produced whenever dyn.load repairs the control word damaged by a buggy DLL.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Examples

options() # printing all current options
op <- options(); str(op) # nicer printing

options('width')[[1]] == options()$width # the latter needs more memory
options(digits = 20)
pi

# set the editor, and save previous value
old.o <- options(editor = "nedit")
old.o

options(check.bounds = TRUE, warn = 1)
x <- NULL; x[4] <- "yes" # gives a warning

options(digits=5)
print(1e5)
options(scipen=3); print(1e5)

options(op)     # reset (all) initial options
options('digits')

## Not run:
## set contrast handling to be like S
options(contrasts = c("contr.helmert", "contr.poly"))
## End(Not run)
## Not run:
## on error, terminate the R session with error status 66
options(error = quote(q("no", status=66, runLast=FALSE)))
stop("test it")
## End(Not run)
## Not run:
## Set error actions for debugging:
## enter browser on error, see ?recover:
options(error = recover)
## allows to call debugger() afterwards, see ?debugger:
options(error = dump.frames)
## A possible setting for non-interactive sessions
options(error = quote({dump.frames(to.file=TRUE); q()}))
## End(Not run)


Ordering Permutation

Description

order returns a permutation which rearranges its first argument into ascending or descending order, breaking ties by further arguments. sort.list is the same, using only one argument.
See the examples for how to use these functions to sort data frames, etc.

Usage

order(..., na.last = TRUE, decreasing = FALSE)

sort.list(x, partial = NULL, na.last = TRUE, decreasing = FALSE,
          method = c("shell", "quick", "radix"))

Arguments

... | a sequence of numeric, complex, character or logical vectors, all of the same length.
x | a vector.
partial | vector of indices for partial sorting. (Non-NULL values are not implemented.)
decreasing | logical. Should the sort order be increasing or decreasing?
na.last | for controlling the treatment of NAs. If TRUE, missing values in the data are put last; if FALSE, they are put first; if NA, they are removed.
method | the method to be used: partial matches are allowed.

Details

In the case of ties in the first vector, values in the second are used to break the ties. If the values are still tied, values in the later arguments are used to break the tie (see the first example). The sort used is stable (except for method = "quick"), so any unresolved ties will be left in their original ordering.

Complex values are sorted first by the real part, then the imaginary part.

The sort order for character vectors will depend on the collating sequence of the locale in use: see Comparison.

The default method for sort.list is a good compromise. Method "quick" is only supported for numeric x with na.last=NA, and is not stable, but will be faster for long vectors. Method "radix" is only implemented for integer x with a range of less than 100,000. For such x it is very fast (and stable), and hence is ideal for sorting factors.

partial is supplied for compatibility with other implementations of S, but no other values are accepted and ordering is always complete.

Note that these functions are only defined for vectors, so any class of the object supplied is ignored: this means factors are sorted on their internal codes and not their printed representation.

Note

sort.list can get called by mistake as a method for sort with a list argument, and gives a suitable error message for list x.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

sort and rank.

Examples

(ii <- order(x <- c(1,1,3:1,1:4,3), y <- c(9,9:1), z <-c(2,1:9)))
## 6  5  2  1  7  4 10  8  3  9
rbind(x,y,z)[,ii] # shows the reordering (ties via 2nd & 3rd arg)

## Suppose we wanted descending order on y. A simple solution is
rbind(x,y,z)[, order(x, -y, z)]
## For character vectors we can make use of rank:
cy <- as.character(y)
rbind(x,y,z)[, order(x, -rank(cy), z)]

## Sorting data frames:
dd <- transform(data.frame(x,y,z),
                z = factor(z, labels=LETTERS[9:1]))
## Either as above {for factor 'z' : using internal coding}:
dd[ order(x, -y, z) ,]
## or along 1st column, ties along 2nd, ... *arbitrary* no.{columns}:
dd[ do.call(order, dd) ,]

set.seed(1)# reproducible example:
d4 <- data.frame(x = round(   rnorm(100)), y = round(10*runif(100)),
                 z = round( 8*rnorm(100)), u = round(50*runif(100)))
(d4s <- d4[ do.call(order, d4) ,])
(i <- which(diff(d4s[,3]) == 0))# in 2 places, needed 3 cols to break ties:
d4s[ rbind(i,i+1), ]

## rearrange matched vectors so that the first is in ascending order
x <- c(5:1, 6:8, 12:9)
y <- (x - 5)^2
o <- order(x)
rbind(x[o], y[o])

## tests of na.last
a <- c(4, 3, 2, NA, 1)
b <- c(4, NA, 2, 7, 1)
z <- cbind(a, b)
(o <- order(a, b)); z[o, ]
(o <- order(a, b, na.last = FALSE)); z[o, ]
(o <- order(a, b, na.last = NA)); z[o, ]

## Not run:
##  speed examples for long vectors:
x <- factor(sample(letters, 1e6, replace=TRUE))
system.time(o <- sort.list(x)) ## 1.2 secs
stopifnot(!is.unsorted(x[o]))
system.time(o <- sort.list(x, method="quick", na.last=NA)) # 0.15 sec
stopifnot(!is.unsorted(x[o]))
system.time(o <- sort.list(x, method="radix")) # 0.02 sec
stopifnot(!is.unsorted(x[o]))
xx <- sample(1:26, 1e7, replace=TRUE)
system.time(o <- sort.list(xx, method="radix")) # 0.2 sec
xx <- sample(1:100000, 1e7, replace=TRUE)
system.time(o <- sort.list(xx, method="radix")) # 0.8 sec
system.time(o <- sort.list(xx, method="quick", na.last=NA)) # 1.4 sec
## End(Not run)


Outer Product of Arrays

Description

The outer product of the arrays X and Y is the array A with dimension c(dim(X), dim(Y)) where element A[c(arrayindex.x, arrayindex.y)] = FUN(X[arrayindex.x], Y[arrayindex.y], ...).

Usage

outer(X, Y, FUN="*", ...)
X %o% Y

Arguments

X, Y | First and second arguments for function FUN. Typically a vector or array.
FUN | a function to use on the outer products, found via match.fun (except for the special case "*").
... | optional arguments to be passed to FUN.

Details

FUN must be a function (or the name of it) which expects at least two arguments and which operates elementwise.

X and Y must be suitable arguments for FUN. Each will be extended by rep to length the products of the lengths of X and Y before FUN is called.

Where they exist, the [dim]names of X and Y will be copied to the answer, and a dimension assigned which is the concatenation of the dimensions of X and Y (or lengths if dimensions do not exist).

FUN = "*" is handled internally as a special case, via as.vector(X) %*% t(as.vector(Y)), and is intended only for numeric vectors and arrays.

%o% is binary operator providing a wrapper for outer(x, y, "*").

Author(s)

Jonathan Rougier

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

%*% for usual (inner) matrix vector multiplication; kronecker which is based on outer.

Examples

x <- 1:9; names(x) <- x
# Multiplication & Power Tables
x %o% x
y <- 2:8; names(y) <- paste(y,":",sep="")
outer(y, x, "^")

outer(month.abb, 1999:2003, FUN = "paste")

## three way multiplication table:
x %o% x %o% y[1:3]


Package versions

Description

A simple S3 class for representing package versions, and associated methods.

Usage

package_version(x, strict = TRUE)

getRversion()

Arguments

x | a character vector with package version strings, or an R version object as obtained by R.version.
strict | a logical indicating whether invalid package versions should results in an error (default) or not.

Details

R (package) versions are sequences of at least two non-negative integers, usually (e.g., in package ‘DESCRIPTION’ files) represented as character strings with the elements of the sequence concatenated and separated by single . or - characters.

package_version creates a representation from such strings which allows for coercion and testing, combination, comparison, summaries (min/max), inclusion in data frames, subscripting, and printing.

getRversion returns the version of the running R as an object of class "package_version".

See Also

compareVersion

Examples

x <- package_version(c("1.2-4", "1.2-3", "2.1"))
x < "1.4-2.3"
c(min(x), max(x))
x[2, 2]
x$major
x$minor


Parentheses and Braces

Description

Open parenthesis, (, and open brace, {, are .Primitive functions in R.

Effectively, ( is semantically equivalent to the identity function(x) x, whereas { is slightly more interesting, see examples.

Usage

( ... )

{ ... }

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

if, return, etc for other objects used in the R language itself.

Syntax for operator precedence.

Examples

f <- get("(")
e <- expression(3 + 2 * 4)
identical(f(e), e)

do <- get("{")
do(x <- 3, y <- 2*x-3, 6-x-y); x; y


Parse Expressions

Description

parse returns the parsed but unevaluated expressions in a list.

Usage

parse(file = "", n = NULL, text = NULL, prompt = "?")

Arguments

file | a connection, or a character string giving the name of a file or a URL to read the expressions from. If file is "" and text is missing or NULL then input is taken from the console.
n | integer (or coerced to integer). The maximum number of expressions to parse. If n is NULL or negative or NA the input is parsed in its entirety.
text | character vector. The text to parse. Elements are treated as if they were lines of a file. Other R objects will be coerced to character (without method dispatch) if possible.
prompt | the prompt to print when parsing from the keyboard. NULL means to use R's prompt, getOption("prompt").

Details

If text has length greater than zero (after coercion) it is used in preference to file.

All versions of R accept input from a connection with end of line marked by LF (as used on Unix), CRLF (as used on DOS/Windows) or CR (as used on classic MacOS). The final line can be incomplete, that is missing the final EOL marker.

See source for the limits on the size of functions that can be parsed (by default). There is also a limit of 8192 bytes on the size of strings which can be parsed.

When input is taken from the console, n = NULL is equivalent to n = 1, and n < 0 will read until an EOF character is read. (The EOF character is Ctrl-Z for the Windows front-ends.)

Value

An object of type "expression", with up to n elements if specified as a non-negative integer.
A syntax error (including an incomplete expression) will throw an error.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

scan, source, eval, deparse.

Examples

cat("x <- c(1,4)\n  x ^ 3 -10 ; outer(1:7,5:9)\n", file="xyz.Rdmped")
# parse 3 statements from the file "xyz.Rdmped"
parse(file = "xyz.Rdmped", n = 3)
unlink("xyz.Rdmped")


Concatenate Strings

Description

Concatenate vectors after converting to character.

Usage

paste(..., sep = " ", collapse = NULL)

Arguments

... | one or more R objects, to be converted to character vectors.
sep | a character string to separate the terms.
collapse | an optional character string to separate the results.

Details

paste converts its arguments (via as.character) to character strings, and concatenates them (separating them by the string given by sep). If the arguments are vectors, they are concatenated term-by-term to give a character vector result. Vector arguments are recycled as needed, with zero-length arguments being recycled to "".

If a value is specified for collapse, the values in the result are then concatenated into a single string, with the elements being separated by the value of collapse.

Value

A character vector of the concatenated values. This will be of length zero if all the objects are, unless collapse is non-NULL, in which case it is a single empty string.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

String manipulation with as.character, substr, nchar, strsplit; further, cat which concatenates and writes to a file, and sprintf for C like string construction.

Examples

paste(1:12) # same as as.character(1:12)
paste("A", 1:6, sep = "")
paste("Today is", date())


Expand File Paths

Description

Expand a path name, for example by replacing a leading tilde by the user's home directory (if defined on that platform).

Usage

path.expand(path)

Arguments

path character vector containing one or more path names.

See Also

basename

Examples

path.expand("~/foo")


Platform Specific Variables

Description

.Platform is a list with some details of the platform under which R was built. This provides means to write OS-portable R code.

Usage

.Platform

Value

A list with at least the following components:

OS.type | character, giving the Operating System (family) of the computer. One of "unix" or "windows".
file.sep | character, giving the file separator used on your platform: "/" on both Unix-alikes and on Windows (but not on the now abandoned port to Classic MacOS).
dynlib.ext | character, giving the file name extension of dynamically loadable libraries, e.g., ".dll" on Windows and ".so" or ".sl" on Unix-alikes. (Note for MacOS X users: these are shared objects as loaded by dyn.load and not dylibs.)
GUI | character, giving the type of GUI in use, or "unknown" if no GUI can be assumed.
endian | character, "big" or "little", giving the endianness of the processor in use. This is relevant when it is necessary to know the order to read/write bytes of e.g. an integer or double from/to a connection: see readBin.
pkgType | character, the preferred setting for options("pkgType"). Values "source", "mac.binary" and "win.binary" are currently in use.
path.sep | character, giving the path separator, used on your platform, e.g., ":" on Unix-alikes and ";" on Windows. Used to separate paths in variables such as PATH and TEXINPUTS.
r_arch | character, posssibly "". The name of the architecture-specific directories used in this build of R.

See Also

R.version and Sys.info give more details about the OS. In particular, R.version$platform is the canonical name of the platform under which R was compiled.

.Machine for details of the arithmetic used, and system for invoking platform-specific system commands.

Examples

## Note: this can be done in a system-independent way by file.info()$isdir
if(.Platform$OS.type == "unix") {
   system.test <- function(...) { system(paste("test", ...)) == 0 }
   dir.exists <- function(dir) sapply(dir, function(d)system.test("-d", d))
   dir.exists(c(R.home(), "/tmp", "~", "/NO"))# > T T T F
}


Partial String Matching

Description

pmatch seeks matches for the elements of its first argument among those of its second.

Usage

pmatch(x, table, nomatch = NA, duplicates.ok = FALSE)

Arguments

x | the values to be matched: converted to a character vector by as.character.
table | the values to be matched against: converted to a character vector.
nomatch | the value to be returned at non-matching or multiply partially matching positions.
duplicates.ok | should elements be in table be used more than once?

Details

The behaviour differs by the value of duplicates.ok. Consider first the case if this is true. First exact matches are considered, and the positions of the first exact matches are recorded. Then unique partial matches are considered, and if found recorded. (A partial match occurs if the whole of the element of x matches the beginning of the element of table.) Finally, all remaining elements of x are regarded as unmatched. In addition, an empty string can match nothing, not even an exact match to an empty string. This is the appropriate behaviour for partial matching of character indices, for example.

If duplicates.ok is FALSE, values of table once matched are excluded from the search for subsequent matches. This behaviour is equivalent to the R algorithm for argument matching, except for the consideration of empty strings (which in argument matching are matched after exact and partial matching to any remaining arguments).

charmatch is similar to pmatch with duplicates.ok true, the differences being that it differentiates between no match and an ambiguous partial match, it does match empty strings, and it does not allow multiple exact matches.

NA values are treated as if they were the string constant "NA".

Value

A numeric vector of integers (including NA if nomatch = NA) of the same length as x, giving the indices of the elements in table which matched, or nomatch.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language. Springer.

See Also

match, charmatch and match.arg, match.fun, match.call, for function argument matching etc., grep etc for more general (regexp) matching of strings.

Examples

pmatch("", "")                             # returns NA
pmatch("m",   c("mean", "median", "mode")) # returns NA
pmatch("med", c("mean", "median", "mode")) # returns 2

pmatch(c("", "ab", "ab"), c("abc", "ab"), dup=FALSE)
pmatch(c("", "ab", "ab"), c("abc", "ab"), dup=TRUE)
## compare
charmatch(c("", "ab", "ab"), c("abc", "ab"))


Find Zeros of a Real or Complex Polynomial

Description

Find zeros of a real or complex polynomial.

Usage

polyroot(z)

Arguments

z the vector of polynomial coefficients in increasing order.

Details

A polynomial of degree n - 1,

p(x) = z1 + z2 * x + ... + z[n] * x^(n-1)

is given by its coefficient vector z[1:n]. polyroot returns the n-1 complex zeros of p(x) using the Jenkins-Traub algorithm.

If the coefficient vector z has zeroes for the highest powers, these are discarded.

Value

A complex vector of length n - 1, where n is the position of the largest non-zero element of z.

References

Jenkins and Traub (1972) TOMS Algorithm 419. Comm. ACM, 15, 97–99.

See Also

uniroot for numerical root finding of arbitrary functions; complex and the zero example in the demos directory.

Examples

polyroot(c(1, 2, 1))
round(polyroot(choose(8, 0:8)), 11) # guess what!
for (n1 in 1:4) print(polyroot(1:n1), digits = 4)
polyroot(c(1, 2, 1, 0, 0)) # same as the first


Convert Positions in the Search Path to Environments

Description

Returns the environment at a specified position in the search path.

Usage

pos.to.env(x)

Arguments

x an integer between 1 and length(search()), the length of the search path.

Details

Several R functions for manipulating objects in environments (such as get and ls) allow specifying environments via corresponding positions in the search path. pos.to.env is a convenience function for programmers which converts these positions to corresponding environments; users will typically have no need for it.

Examples

pos.to.env(1) # R_GlobalEnv
# the next returns the base environment
pos.to.env(length(search()))


Pretty Breakpoints

Description

Compute a sequence of about n+1 equally spaced nice values which cover the range of the values in x. The values are chosen so that they are 1, 2 or 5 times a power of 10.

Usage

pretty(x, n = 5, min.n = n %/% 3,  shrink.sml = 0.75,
       high.u.bias = 1.5, u5.bias = .5 + 1.5*high.u.bias,
       eps.correct = 0)

Arguments

x | numeric vector
n | integer giving the desired number of intervals. Non-integer values are rounded down.
min.n | nonnegative integer giving the minimal number of intervals. If min.n == 0, pretty(.) may return a single value.
shrink.sml | positive numeric by a which a default scale is shrunk in the case when range(x) is “very small” (usually 0).
high.u.bias | non-negative numeric, typically > 1. The interval unit is determined as {1,2,5,10} times b, a power of 10. Larger high.u.bias values favor larger units.
u5.bias | non-negative numeric multiplier favoring factor 5 over 2. Default and “optimal”: u5.bias = .5 + 1.5*high.u.bias.
eps.correct | integer code, one of {0,1,2}. If non-0, an “epsilon correction” is made at the boundaries such that the result boundaries will be outside range(x); in the small case, the correction is only done if eps.correct >=2.

Details

pretty ignores non-finite values in x.

Let d <- max(x) - min(x) >= 0. If d is not (very close) to 0, we let c <- d/n, otherwise more or less c <- max(abs(range(x)))*shrink.sml / min.n. Then, the 10 base b is 10^(floor(log10(c))) such that b <= c < 10b.

Now determine the basic unit u as one of {1,2,5,10} b, depending on c/b in [1,10) and the two “bias” coefficients, h =high.u.bias and f =u5.bias.

.........

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

axTicks for the computation of pretty axis tick locations in plots, particularly on the log scale.

Examples

pretty(1:15)     # 0  2  4  6  8 10 12 14 16
pretty(1:15, h=2)# 0  5 10 15
pretty(1:15, n=4)# 0  5 10 15
pretty(1:15 * 2) # 0  5 10 15 20 25 30
pretty(1:20)      # 0  5 10 15 20
pretty(1:20, n=2) # 0 10 20
pretty(1:20, n=10)# 0  2  4 ... 20

for(k in 5:11) {
  cat("k=",k,": "); print(diff(range(pretty(100 + c(0, pi*10^-k)))))}

##-- more bizarre, when  min(x) == max(x):
pretty(pi)

add.names <- function(v) { names(v) <- paste(v); v}
str(lapply(add.names(-10:20), pretty))
str(lapply(add.names(0:20),   pretty, min = 0))
sapply(    add.names(0:20),   pretty, min = 4)

pretty(1.234e100)
pretty(1001.1001)
pretty(1001.1001, shrink = .2)
for(k in -7:3)
  cat("shrink=",formatC(2^k,wid=9),":",
      formatC(pretty(1001.1001, shrink = 2^k), wid=6),"\n")


Call a “Primitive” Internal Function

Description

.Primitive returns an entry point to a “primitive” (internally implemented) function.

Usage

.Primitive(name)

Arguments

name name of the R function.

Details

The advantage of .Primitive over .Internal functions is the potential efficiency of argument passing. However, this is done by ignoring argument names and using positional matching of arguments (unless arranged differently for specific primitives such as rep), so this is discouraged for functions of more than one argument.

All primitive functions are in the base name space.

See Also

.Internal.

Examples

mysqrt <- .Primitive("sqrt")
c
.Internal # this one *must* be primitive!
get("if") # just 'if' or 'print(if)' are not syntactically ok.


Print Values

Description

print prints its argument and returns it invisibly (via invisible(x)). It is a generic function which means that new printing methods can be easily added for new classes.

Usage

print(x, ...)

## S3 method for class 'factor':
print(x, quote = FALSE, max.levels = NULL,
      width = getOption("width"), ...)

## S3 method for class 'table':
print(x, digits = getOption("digits"), quote = FALSE,
      na.print = "", zero.print = "0", justify = "none", ...)

Arguments

x | an object used to select a method.
... | further arguments passed to or from other methods.
quote | logical, indicating whether or not strings should be printed with surrounding quotes.
max.levels | integer, indicating how many levels should be printed for a factor; if 0, no extra "Levels" line will be printed. The default, NULL, entails choosing max.levels such that the levels print on one line of width width.
width | only used when max.levels is NULL, see above.
digits | minimal number of significant digits, see print.default.
na.print | character string (or NULL) indicating NA values in printed output, see print.default.
zero.print | character specifying how zeros (0) should be printed; for sparse tables, using "." can produce stronger results.
justify | character indicating if strings should left- or right-justified or left alone, passed to format.

Details

The default method, print.default has its own help page. Use methods("print") to get all the methods for the print generic.

print.factor allows some customization and is used for printing ordered factors as well.

print.table for printing tables allows other customization.

See noquote as an example of a class whose main purpose is a specific print method.

References

Chambers, J. M. and Hastie, T. J. (1992) Statistical Models in S. Wadsworth & Brooks/Cole.

See Also

The default method print.default, and help for the methods above; further options, noquote.

For more customizable (but cumbersome) printing, see cat, format or also write.

Examples

ts(1:20)#-- print is the "Default function" --> print.ts(.) is called
rr <- for(i in 1:3) print(1:i)
rr

## Printing of factors
attenu$station ## 117 levels -> `max.levels' depending on width

## ordered factors: levels  "l1 < l2 < .."
esoph$agegp[1:12]
esoph$alcgp[1:12]

## Printing of sparse (contingency) tables
set.seed(521)
t1 <- round(abs(rt(200, df=1.8)))
t2 <- round(abs(rt(200, df=1.4)))
table(t1,t2) # simple
print(table(t1,t2), zero.print = ".")# nicer to read


Printing Data Frames

Description

Print a data frame.

Usage

## S3 method for class 'data.frame':
print(x, ..., digits = NULL, quote = FALSE, right = TRUE)

Arguments

x | object of class data.frame.
... | optional arguments to print or plot methods.
digits | the minimum number of significant digits to be used: see print.default.
quote | logical, indicating whether or not entries should be printed with surrounding quotes.
right | logical, indicating whether or not strings should be right-aligned. The default is right-alignment.

Details

This calls format which formats the data frame column-by-column, then converts to a character matrix and dispatches to the print method for matrices.

When quote = TRUE only the entries are quoted not the row names nor the column names.

See Also

data.frame.


Default Printing

Description

print.default is the default method of the generic print function which prints its argument.

Usage

## Default S3 method:
print(x, digits = NULL, quote = TRUE, na.print = NULL,
      print.gap = NULL, right = FALSE, max = NULL, ...)

Arguments

x | the object to be printed.
digits | a non-null value for digits specifies the minimum number of significant digits to be printed in values. The default, NULL, uses getOption(digits). (For the interpretation for complex numbers see signif.) Non-integer values will be rounded down, and only values greater than or equal to one are accepted.
quote | logical, indicating whether or not strings (characters) should be printed with surrounding quotes.
na.print | a character string which is used to indicate NA values in printed output, or NULL (see Details)
print.gap | a non-negative integer <= 1024, or NULL (meaning 1), giving the spacing between adjacent “columns” in printed vectors, matrices and arrays.
right | logical, indicating whether or not strings should be right aligned. The default is left alignment.
max | a non-null value for max specifies the approximate maximum number of entries to be printed. The default, NULL, uses getOption(max.print); see that help page for more details.
... | further arguments to be passed to or from other methods. They are ignored in this function.

Details

The default for printing NAs is to print NA (without quotes) unless this is a character NA and quote = FALSE, when <NA> is printed.

The same number of decimal places is used throughout a vector, This means that digits specifies the minimum number of significant digits to be used, and that at least one entry will be encoded with that minimum number. However, if all the encoded elements then have trailing zeroes, the number of decimal places is reduced until at least one element has a non-zero final digit. Decimal points are only included if at least one decimal place is selected.

Attributes are printed respecting their class(es), using the values of digits to print.default, but using the default values (for the methods called) of the other arguments.

When the methods package is attached, print will call show for R objects with formal classes if called with no optional arguments.

Single-byte locales

If a non-printable character is encountered during output, it is represented as one of the ANSI escape sequences (\a, \b, \f, \n, \r, \t, \v, \\ and \0: see Quotes), or failing that as a 3-digit octal code: for example the UK currency pound sign in the C locale (if implemented correctly) is printed as \243. Which characters are non-printable depends on the locale. (Because some versions of Windows get this wrong, all bytes with the upper bit set are regarded as printable on Windows in a single-byte locale.)

Multi-byte locales

In all locales, the characters in the ASCII range (0x00 to 0x7f) are printed in the same way, as-is if printable, otherwise via ANSI escape sequences or 3-digit octal escapes as described for single-byte locales.

Multi-byte non-printing characters are printed as an escape sequence of the form \uxxxx (in hexadecimal). This is the Unicode point of the character.

It is possible to have a character string in a character vector that is not valid in the current locale. If a byte is encountered that is not part of a valid character it is printed in hex in the form <xx> and this is repeated until the start of a valid character.

See Also

The generic print, options. The "noquote" class and print method.

encodeString, which encodes a character vector the way it would be printed.

Examples

pi
print(pi, digits = 16)
LETTERS[1:16]
print(LETTERS, quote = FALSE)

M <- cbind(I=1, matrix(1:10000, nc=10, dimnames=list(NULL, LETTERS[1:10])))
head(M) # makes more sense than
print(M, max= 1000)# prints 90 rows and a message about omitting 910


Print Matrices, Old-style

prmatrix(base) R Documentation

Print Matrices Old-style

Description

An earlier method for printing matrices, provided for S compatibility.

Usage

prmatrix(x, rowlab =, collab =,
         quote = TRUE, right = FALSE, na.print = NULL, ...)

Arguments

x | numeric or character matrix.
rowlab,collab | (optional) character vectors giving row or column names respectively. By default, these are taken from dimnames(x).
quote | logical; if TRUE and x is of mode "character", quotes (") are used.
right | if TRUE and x is of mode "character", the output columns are right-justified.
na.print | how NAs are printed. If this is non-null, its value is used to represent NA.
... | arguments for print methods.

Details

prmatrix is an earlier form of print.matrix, and is very similar to the S function of the same name.

Value

Invisibly returns its argument, x.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

print.default, and other print methods.

Examples

prmatrix(m6 <- diag(6), row = rep("",6), coll=rep("",6))

chm <- matrix(scan(system.file("help", "AnIndex", package = "splines"),
                   what = ""), , 2, byrow = TRUE)
chm  # uses print.matrix()
prmatrix(chm, collab = paste("Column",1:3), right=TRUE, quote=FALSE)


Running Time of R

Description

proc.time determines how much time (in seconds) the currently running R process already consumed.

Usage

proc.time()

Value

A numeric vector of length 5, containing the user, system, and total elapsed times for the currently running R process, and the cumulative sum of user and system times of any child processes spawned by it.
The resolution of the times will be system-specific; and times are typically available to 10ms on NT-based versions of Windows.
It is most useful for “timing” the evaluation of R expressions, which can be done conveniently with system.time.

Note

CPU times will be returned as NA on Windows 9x/ME systems, but are genuine times on NT4/2000/XP systems. Times of child processes are not available and will always be given as NA.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

system.time for timing a valid R expression, gc.time for how much of the time was spent in garbage collection.

Examples

## Not run:
## a way to time an R expression: system.time is preferred
ptm <- proc.time()
for (i in 1:50) mad(runif(500))
proc.time() - ptm
## End(Not run)


Product of Vector Elements

Description

prod returns the product of all the values present in its arguments.

Usage

prod(..., na.rm = FALSE)

Arguments

... | numeric or complex or logical vectors.
na.rm | logical. Should missing values be removed?

Details

If na.rm is FALSE an NA value in any of the arguments will cause a value of NA to be returned, otherwise NA values are ignored.

This is a generic function: methods can be defined for it directly or via the Summary group generic. For this to work properly, the arguments ... should be unnamed, and dispatch is on the first argument.

Logical true values are regarded as one, false values as zero. For historical reasons, NULL is accepted and treated as if it were numeric(0).

Value

The product, a numeric (of type "double") or complex vector of length one. NB: the product of an empty set is one, by definition.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

sum, cumprod, cumsum.

Examples

print(prod(1:7)) == print(gamma(8))


Express Table Entries as Fraction of Marginal Table

Description

This is really sweep(x, margin, margin.table(x, margin), "/") for newbies, except that if margin has length zero, then one gets x/sum(x).

Usage

prop.table(x, margin=NULL)

Arguments

x | table
margin | index, or vector of indices to generate margin for

Value

Table like x expressed relative to margin

Author(s)

Peter Dalgaard

See Also

margin.table

Examples

m <- matrix(1:4,2)
m
prop.table(m,1)


Push Text Back on to a Connection

Description

Functions to push back text lines onto a connection, and to enquire how many lines are currently pushed back.

Usage

pushBack(data, connection, newLine = TRUE)
pushBackLength(connection)

Arguments

data | a character vector.
connection | A connection.
newLine | logical. If true, a newline is appended to each string pushed back.

Details

Several character strings can be pushed back on one or more occasions. The occasions form a stack, so the first line to be retrieved will be the first string from the last call to pushBack. Lines which are pushed back are read prior to the normal input from the connection, by the normal text-reading functions such as readLines and scan.

Pushback is only allowed for readable connections.

Not all uses of connections respect pushbacks, in particular the input connection is still wired directly, so for example parsing commands from the console and scan("") ignore pushbacks on stdin.

Value

pushBack returns nothing.
pushBackLength returns number of lines currently pushed back.

See Also

connections, readLines.

Examples

zz <- textConnection(LETTERS)
readLines(zz, 2)
pushBack(c("aa", "bb"), zz)
pushBackLength(zz)
readLines(zz, 1)
pushBackLength(zz)
readLines(zz, 1)
readLines(zz, 1)
close(zz)


Set Environment Variables

Description

putenv sets environment variables (for other processes called from within R or future calls to Sys.getenv from this R process).

Usage

Sys.putenv(...)

Arguments

... arguments in name=value form, with value coercible to a character string.

Details

Non-standard R names must be quoted: see the Examples section.

Value

A logical vector of the same length as x, with elements being true if setting the corresponding variable succeeded.

Note

Not all systems need support Sys.putenv (although all known current platforms do).

See Also

Sys.getenv, Startup for ways to set environment variables for the R session.

setwd for the working directory.

Examples

print(Sys.putenv(R_TEST="testit", "A+C"=123))
Sys.getenv("R_TEST")


The QR Decomposition of a Matrix

Description

qr computes the QR decomposition of a matrix. It provides an interface to the techniques used in the LINPACK routine DQRDC or the LAPACK routines DGEQP3 and (for complex matrices) ZGEQP3.

Usage

qr(x, tol = 1e-07 , LAPACK = FALSE)
qr.coef(qr, y)
qr.qy(qr, y)
qr.qty(qr, y)
qr.resid(qr, y)
qr.fitted(qr, y, k = qr$rank)
qr.solve(a, b, tol = 1e-7)
## S3 method for class 'qr':
solve(a, b, ...)

is.qr(x)
as.qr(x)

Arguments

x | a matrix whose QR decomposition is to be computed.
tol | the tolerance for detecting linear dependencies in the columns of x. Only used if LAPACK is false and x is real.
qr | a QR decomposition of the type computed by qr.
y, b | a vector or matrix of right-hand sides of equations.
a | A QR decomposition or (qr.solve only) a rectangular matrix.
k | effective rank.
LAPACK | logical. For real x, if true use LAPACK otherwise use LINPACK.
... | further arguments passed to or from other methods

Details

The QR decomposition plays an important role in many statistical techniques. In particular it can be used to solve the equation Ax = b for given matrix A, and vector b. It is useful for computing regression coefficients and in applying the Newton-Raphson algorithm.

The functions qr.coef, qr.resid, and qr.fitted return the coefficients, residuals and fitted values obtained when fitting y to the matrix with QR decomposition qr. qr.qy and qr.qty return Q %*% y and t(Q) %*% y, where Q is the (complete) Q matrix.

All the above functions keep dimnames (and names) of x and y if there are.

solve.qr is the method for solve for qr objects. qr.solve solves systems of equations via the QR decomposition: if a is a QR decomposition it is the same as solve.qr, but if a is a rectangular matrix the QR decomposition is computed first. Either will handle over- and under-determined systems, providing a minimal-length solution or a least-squares fit if appropriate.

is.qr returns TRUE if x is a list with components named qr, rank and qraux and FALSE otherwise.

It is not possible to coerce objects to mode "qr". Objects either are QR decompositions or they are not.

Value

The QR decomposition of the matrix as computed by LINPACK or LAPACK. The components in the returned value correspond directly to the values returned by DQRDC/DGEQP3/ZGEQP3.

qr | a matrix with the same dimensions as x. The upper triangle contains the R of the decomposition and the lower triangle contains information on the Q of the decomposition (stored in compact form). Note that the storage used by DQRDC and DGEQP3 differs.
qraux | a vector of length ncol(x) which contains additional information on Q.
rank | the rank of x as computed by the decomposition: always full rank in the LAPACK case.
pivot | information on the pivoting strategy used during the decomposition.

Non-complex QR objects computed by LAPACK have the attribute "useLAPACK" with value TRUE.

Note

To compute the determinant of a matrix (do you really need it?), the QR decomposition is much more efficient than using Eigen values (eigen). See det.

Using LAPACK (including in the complex case) uses column pivoting and does not attempt to detect rank-deficient matrices.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Dongarra, J. J., Bunch, J. R., Moler, C. B. and Stewart, G. W. (1978) LINPACK Users Guide. Philadelphia: SIAM Publications.

Anderson. E. and ten others (1999) LAPACK Users' Guide. Third Edition. SIAM.
Available on-line at http://www.netlib.org/lapack/lug/lapack_lug.html.

See Also

qr.Q, qr.R, qr.X for reconstruction of the matrices. lm.fit, lsfit, eigen, svd.

det (using qr) to compute the determinant of a matrix.

Examples

hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
h9 <- hilbert(9); h9
qr(h9)$rank           #--> only 7
qrh9 <- qr(h9, tol = 1e-10)
qrh9$rank             #--> 9
##-- Solve linear equation system  H %*% x = y :
y <- 1:9/10
x <- qr.solve(h9, y, tol = 1e-10) # or equivalently :
x <- qr.coef(qrh9, y) #-- is == but much better than
                      #-- solve(h9) %*% y
h9 %*% x              # = y


Reconstruct the Q, R, or X Matrices from a QR Object

QR.Auxiliaries(base) R Documentation

Reconstruct the Q R or X Matrices from a QR Object

Description

Returns the original matrix from which the object was constructed or the components of the decomposition.

Usage

qr.X(qr, complete = FALSE, ncol =)
qr.Q(qr, complete = FALSE, Dvec =)
qr.R(qr, complete = FALSE)

Arguments

qr | object representing a QR decomposition. This will typically have come from a previous call to qr or lsfit.
complete | logical expression of length 1. Indicates whether an arbitrary orthogonal completion of the Q or X matrices is to be made, or whether the R matrix is to be completed by binding zero-value rows beneath the square upper triangle.
ncol | integer in the range 1:nrow(qr$qr). The number of columns to be in the reconstructed X. The default when complete is FALSE is the first min(ncol(X), nrow(X)) columns of the original X from which the qr object was constructed. The default when complete is TRUE is a square matrix with the original X in the first ncol(X) columns and an arbitrary orthogonal completion (unitary completion in the complex case) in the remaining columns.
Dvec | vector (not matrix) of diagonal values. Each column of the returned Q will be multiplied by the corresponding diagonal value. Defaults to all 1s.

Value

qr.X returns X, the original matrix from which the qr object was constructed, provided ncol(X) <= nrow(X). If complete is TRUE or the argument ncol is greater than ncol(X), additional columns from an arbitrary orthogonal (unitary) completion of X are returned.
qr.Q returns part or all of Q, the order-nrow(X) orthogonal (unitary) transformation represented by qr. If complete is TRUE, Q has nrow(X) columns. If complete is FALSE, Q has ncol(X) columns. When Dvec is specified, each column of Q is multiplied by the corresponding value in Dvec.
qr.R returns R. The number of rows of R is nrow(X) or ncol(X), depending on whether complete is TRUE or FALSE.

See Also

qr, qr.qy.

Examples

p <- ncol(x <- LifeCycleSavings[,-1]) # not the 'sr'
qrstr <- qr(x)   # dim(x) == c(n,p)
qrstr $ rank # = 4 = p
Q <- qr.Q(qrstr) # dim(Q) == dim(x)
R <- qr.R(qrstr) # dim(R) == ncol(x)
X <- qr.X(qrstr) # X == x
range(X - as.matrix(x))# ~ < 6e-12
## X == Q %*% R if there has been no pivoting, as here.
Q %*% R


Terminate an R Session

Description

The function quit or its alias q terminate the current R session.

Usage

quit(save = "default", status = 0, runLast = TRUE)
   q(save = "default", status = 0, runLast = TRUE)
.Last <- function(x) { ...... }

Arguments

save | a character string indicating whether the environment (workspace) should be saved, one of "no", "yes", "ask" or "default".
status | the (numerical) error status to be returned to the operating system, where relevant. Conventionally 0 indicates successful completion.
runLast | should .Last() be executed?

Details

save must be one of "no", "yes", "ask" or "default". In the first case the workspace is not saved, in the second it is saved and in the third the user is prompted and can also decide not to quit. The default is to ask in interactive use but may be overridden by command-line arguments (which must be supplied in non-interactive use).

Immediately before terminating, the function .Last() is executed if it exists and runLast is true. If in interactive use there are errors in the .Last function, control will be returned to the command prompt, so do test the function thoroughly.

Some error statuses are used by R itself. The default error handler for non-interactive effectively calls q("no", 1, FALSE) and returns error code 1. Error status 2 is used for R ‘suicide’, that is a catastrophic failure, and other small numbers are used by specific ports for initialization failures. It is recommended that users choose statuses of 10 or more.

Valid values of status are system-dependent, but 0:255 are normally valid.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

.First for setting things on startup.

Examples

## Not run:
## Unix-flavour example
.Last <- function() {
  cat("Now sending PostScript graphics to the printer:\n")
  system("lpr Rplots.ps")
  cat("bye bye...\n")
}
quit("yes")
## End(Not run)


Quotes

Description

Descriptions of the various uses of quoting in R.

Details

Three types of quote are part of the syntax of R: single and double quotation marks and the backtick (or back quote, `). In addition, backslash is used for quoting the following character(s) inside character constants.

Character constants

Single and double quotes delimit character constants. They can be used interchangeably but double quotes are preferred (and character constants are printed using double quotes), so single quotes are normally only used to delimit character constants containing double quotes.

Backslash is used to start an escape sequence inside character constants. Unless specified in the following table, an escaped character is interpreted as the character itself. Single quotes need to be escaped by backslash in single-quoted strings, and double quotes in double-quoted strings.

\n | newline
\r | carriage return
\t | tab
\b | backspace
\a | alert (bell)
\f | form feed
\v | vertical tab
\\ | backslash \
\nnn | character with given octal code (1, 2 or 3 digits)
\xnn | character with given hex code (1 or 2 hex digits)
\unnnn | Unicode character with given code (1–4 hex digits)
\Unnnnnnnn | Unicode character with given code (1–8 hex digits)

The last two are only supported on versions of R built with MBCS support, and the last is not supported on Windows. (They are an error if used where not supported.) All except the Unicode escape sequences are also supported when reading character strings from a connection by scan.

These forms will also be used by print.default when outputting non-printable characters (including backslash).

Names and Identifiers

Identifiers consist of a sequence of letters, digits, the period (.) and the underscore. They must not start with a digit nor underscore, nor with a period followed by a digit.

The definition of a letter depends on the current locale, but only ASCII digits are considered to be digits.

Such identifiers are also known as syntactic names and may be used directly in R code. Almost always, other names can be used provided they are quoted. The preferred quote is the backtick (`), and deparse will normally use it, but under many circumstances single or double quotes can be used (as a character constant will often be converted to a name). One place where backticks may be essential is to delimit variable names in formulae: see formula.

See Also

Syntax for other aspects of the syntax.

sQuote for quoting English text.

shQuote for quoting OS commands.

The R Language Definition manual.


Random Number Generation

Description

.Random.seed is an integer vector, containing the random number generator (RNG) state for random number generation in R. It can be saved and restored, but should not be altered by the user.

RNGkind is a more friendly interface to query or set the kind of RNG in use.

RNGversion can be used to set the random generators as they were in an earlier R version (for reproducibility).

set.seed is the recommended way to specify seeds.

Usage

.Random.seed <- c(rng.kind, n1, n2, ...)
save.seed <- .Random.seed

RNGkind(kind = NULL, normal.kind = NULL)
RNGversion(vstr)
set.seed(seed, kind = NULL)

Arguments

kind | character or NULL. If kind is a character string, set R's RNG to the kind desired. If it is NULL, return the currently used RNG. Use "default" to return to the R default.
normal.kind | character string or NULL. If it is a character string, set the method of Normal generation. Use "default" to return to the R default.
seed | a single value, interpreted as an integer.
vstr | a character string containing a version number, e.g., "1.6.2"
rng.kind | integer code in 0:k for the above kind.
n1, n2, ... | integers. See the details for how many are required (which depends on rng.kind).

Details

The currently available RNG kinds are given below. kind is partially matched to this list. The default is "Mersenne-Twister".

"Wichmann-Hill"
The seed, .Random.seed[-1] == r[1:3] is an integer vector of length 3, where each r[i] is in 1:(p[i] - 1), where p is the length 3 vector of primes, p = (30269, 30307, 30323). The Wichmann–Hill generator has a cycle length of 6.9536e12 (= prod(p-1)/4, see Applied Statistics (1984) 33, 123 which corrects the original article).
"Marsaglia-Multicarry":
A multiply-with-carry RNG is used, as recommended by George Marsaglia in his post to the mailing list ‘sci.stat.math’. It has a period of more than 2^60 and has passed all tests (according to Marsaglia). The seed is two integers (all values allowed).
"Super-Duper":
Marsaglia's famous Super-Duper from the 70's. This is the original version which does not pass the MTUPLE test of the Diehard battery. It has a period of about 4.6*10^18 for most initial seeds. The seed is two integers (all values allowed for the first seed: the second must be odd).

We use the implementation by Reeds et al. (1982–84).

The two seeds are the Tausworthe and congruence long integers, respectively. A one-to-one mapping to S's .Random.seed[1:12] is possible but we will not publish one, not least as this generator is not exactly the same as that in recent versions of S-PLUS.

"Mersenne-Twister":
From Matsumoto and Nishimura (1998). A twisted GFSR with period 2^19937 - 1 and equidistribution in 623 consecutive dimensions (over the whole period). The “seed” is a 624-dimensional set of 32-bit integers plus a current position in that set.
"Knuth-TAOCP":
From Knuth (1997). A GFSR using lagged Fibonacci sequences with subtraction. That is, the recurrence used is

X[j] = (X[j-100] - X[j-37]) mod 2^30

and the “seed” is the set of the 100 last numbers (actually recorded as 101 numbers, the last being a cyclic shift of the buffer). The period is around 2^129.

"Knuth-TAOCP-2002":
The 2002 version which not backwards compatible with the earlier version: the initialization of the GFSR from the seed was altered. R did not allow you to choose consecutive seeds, the reported ‘weakness’, and already scrambled the seeds.
"user-supplied":
Use a user-supplied generator. See Random.user for details.

normal.kind can be "Kinderman-Ramage", "Buggy Kinderman-Ramage", "Ahrens-Dieter", "Box-Muller", "Inversion" (the default), or "user-supplied". (For inversion, see the reference in qnorm.) The Kinderman-Ramage generator used in versions prior to 1.7.1 had several approximation errors and should only be used for reproduction of older results.

set.seed uses its single integer argument to set as many seeds as are required. It is intended as a simple way to get quite different seeds by specifying small integer arguments, and also as a way to get valid seed sets for the more complicated methods (especially "Mersenne-Twister" and "Knuth-TAOCP").

Value

.Random.seed is an integer vector whose first element codes the kind of RNG and normal generator. The lowest two decimal digits are in 0:(k-1) where k is the number of available RNGs. The hundreds represent the type of normal generator (starting at 0).
In the underlying C, .Random.seed[-1] is unsigned; therefore in R .Random.seed[-1] can be negative, due to the representation of an unsigned integer by a signed integer.
RNGkind returns a two-element character vector of the RNG and normal kinds in use before the call, invisibly if either argument is not NULL. RNGversion returns the same information.
set.seed returns NULL, invisibly.

Note

Initially, there is no seed; a new one is created from the current time when one is required. Hence, different sessions will give different simulation results, by default.

.Random.seed saves the seed set for the uniform random-number generator, at least for the system generators. It does not necessarily save the state of other generators, and in particular does not save the state of the Box–Muller normal generator. If you want to reproduce work later, call set.seed rather than set .Random.seed.

The object .Random.seed is only looked for in the user's workspace.

All the supplied uniform generators return 32-bit integer values that are converted to doubles, so they take at most 2^32 distinct values and long runs will return duplicated values.

Author(s)

of RNGkind: Martin Maechler. Current implementation, B. D. Ripley

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole. (set.seed, storing in .Random.seed.)

Wichmann, B. A. and Hill, I. D. (1982) Algorithm AS 183: An Efficient and Portable Pseudo-random Number Generator, Applied Statistics, 31, 188–190; Remarks: 34, 198 and 35, 89.

De Matteis, A. and Pagnutti, S. (1993) Long-range Correlation Analysis of the Wichmann-Hill Random Number Generator, Statist. Comput., 3, 67–70.

Marsaglia, G. (1997) A random number generator for C. Discussion paper, posting on Usenet newsgroup sci.stat.math on September 29, 1997.

Reeds, J., Hubert, S. and Abrahams, M. (1982–4) C implementation of SuperDuper, University of California at Berkeley. (Personal communication from Jim Reeds to Ross Ihaka.)

Marsaglia, G. and Zaman, A. (1994) Some portable very-long-period random number generators. Computers in Physics, 8, 117–121.

Matsumoto, M. and Nishimura, T. (1998) Mersenne Twister: A 623-dimensionally equidistributed uniform pseudo-random number generator, ACM Transactions on Modeling and Computer Simulation, 8, 3–30.
Source code at http://www.math.keio.ac.jp/~matumoto/emt.html.

Knuth, D. E. (1997) The Art of Computer Programming. Volume 2, third edition.
Source code at http://www-cs-faculty.stanford.edu/~knuth/taocp.html.

Knuth, D. E. (2002) The Art of Computer Programming. Volume 2, third edition, ninth printing.
See http://Sunburn.Stanford.EDU/~knuth/news02.html.

Kinderman, A. J. and Ramage, J. G. (1976) Computer generation of normal random variables. Journal of the American Statistical Association 71, 893-896.

Ahrens, J.H. and Dieter, U. (1973) Extensions of Forsythe's method for random sampling from the normal distribution. Mathematics of Computation 27, 927-937.

Box, G.E.P. and Muller, M.E. (1958) A note on the generation of normal random deviates. Annals of Mathmatical Statistics 29, 610–611.

See Also

runif, rnorm, ....

Examples

## the default random seed is 626 integers, so only print a few
runif(1); .Random.seed[1:6]; runif(1); .Random.seed[1:6]
## If there is no seed, a "random" new one is created:
rm(.Random.seed); runif(1); .Random.seed[1:6]

RNGkind("Wich")# (partial string matching on 'kind')

## This shows how 'runif(.)' works for Wichmann-Hill,
## using only R functions:

p.WH <- c(30269, 30307, 30323)
a.WH <- c(  171,   172,   170)
next.WHseed <- function(i.seed = .Random.seed[-1])
  { (a.WH * i.seed) %% p.WH }
my.runif1 <- function(i.seed = .Random.seed)
  { ns <- next.WHseed(i.seed[-1]); sum(ns / p.WH) %% 1 }
rs <- .Random.seed
(WHs <- next.WHseed(rs[-1]))
u <- runif(1)
stopifnot(
 next.WHseed(rs[-1]) == .Random.seed[-1],
 all.equal(u, my.runif1(rs))
)

## ----
.Random.seed
ok <- RNGkind()
RNGkind("Super")#matches  "Super-Duper"
RNGkind()
.Random.seed # new, corresponding to  Super-Duper

## Reset:
RNGkind(ok[1])

## ----
sum(duplicated(runif(1e6))) # around 110
## and we would expect about almost sure duplicates beyond about
qbirthday(1-1e-6, classes=2e9) # 235,000


User-supplied Random Number Generation

Description

Function RNGkind allows user-coded uniform and normal random number generators to be supplied. The details are given here.

Details

A user-specified uniform RNG is called from entry points in dynamically-loaded compiled code. The user must supply the entry point user_unif_rand, which takes no arguments and returns a pointer to a double. The example below will show the general pattern.

Optionally, the user can supply the entry point user_unif_init, which is called with an unsigned int argument when RNGkind (or set.seed) is called, and is intended to be used to initialize the user's RNG code. The argument is intended to be used to set the “seeds”; it is the seed argument to set.seed or an essentially random seed if RNGkind is called.

If only these functions are supplied, no information about the generator's state is recorded in .Random.seed. Optionally, functions user_unif_nseed and user_unif_seedloc can be supplied which are called with no arguments and should return pointers to the number of “seeds” and to an integer array of “seeds”. Calls to GetRNGstate and PutRNGstate will then copy this array to and from .Random.seed.

A user-specified normal RNG is specified by a single entry point user_norm_rand, which takes no arguments and returns a pointer to a double.

Warning

As with all compiled code, mis-specifying these functions can crash R. Do include the ‘R_ext/Random.h’ header file for type checking.

Examples

## Not run:
##  Marsaglia's conguential PRNG
#include <R_ext/Random.h>

static Int32 seed;
static double res;
static int nseed = 1;

double * user_unif_rand()
{
    seed = 69069 * seed + 1;
    res = seed * 2.32830643653869e-10;
    return &res;
}

void  user_unif_init(Int32 seed_in) { seed = seed_in; }
int * user_unif_nseed() { return &nseed; }
int * user_unif_seedloc() { return (int *) &seed; }

/*  ratio-of-uniforms for normal  */
#include <math.h>
static double x;

double * user_norm_rand()
{
    double u, v, z;
    do {
        u = unif_rand();
        v = 0.857764 * (2. * unif_rand() - 1);
        x = v/u; z = 0.25 * x * x;
        if (z < 1. - u) break;
        if (z > 0.259/u + 0.35) continue;
    } while (z > -log(u));
    return &x;
}

## Use under Unix:
R CMD SHLIB urand.c
R
> dyn.load("urand.so")
> RNGkind("user")
> runif(10)
> .Random.seed
> RNGkind(, "user")
> rnorm(10)
> RNGkind()
[1] "user-supplied" "user-supplied"
## End(Not run)


Range of Values

Description

range returns a vector containing the minimum and maximum of all the given arguments.

Usage

range(..., na.rm = FALSE)

## Default S3 method:
range(..., na.rm = FALSE, finite = FALSE)

Arguments

... | any numeric objects.
na.rm | logical, indicating if NA's should be omitted.
finite | logical, indicating if all non-finite elements should be omitted.

Details

range is a generic function: methods can be defined for it directly or via the Summary group generic. For this to work properly, the arguments ... should be unnamed, and dispatch is on the first argument.

If na.rm is FALSE, NA and NaN values in any of the arguments will cause NA values to be returned, otherwise NA values are ignored.

If finite is TRUE, the minimum and maximum of all finite values is computed, i.e., finite=TRUE includes na.rm=TRUE.

A special situation occurs when there is no (after omission of NAs) nonempty argument left, see min.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

The extendrange() utility; min, max, Methods.

Examples

(r.x <- range(rnorm(100)))
diff(r.x) # the SAMPLE range

x <- c(NA, 1:3, -1:1/0); x
range(x)
range(x, na.rm = TRUE)
range(x, finite = TRUE)


Sample Ranks

Description

Returns the sample ranks of the values in a vector. Ties, i.e., equal values, result in ranks being averaged, by default.

Usage

rank(x, na.last = TRUE,
     ties.method = c("average", "first", "random", "max", "min"))

Arguments

x | a numeric, complex, character or logical vector.
na.last | for controlling the treatment of NAs. If TRUE, missing values in the data are put last; if FALSE, they are put first; if NA, they are removed; if "keep" they are kept.
ties.method | a character string specifying how ties are treated, see below; can be abbreviated.

Details

If all components are different, the ranks are well defined, with values in 1:n where n <- length(x) and we assume no NAs for the moment. Otherwise, with some values equal, called ‘ties’, the argument ties.method determines the result at the corresponding indices. The "first" method results in a permutation with increasing values at each index set of ties. The "random" method puts these in random order whereas the default, "average", replaces them by their mean, and "max" and "min" replaces them by their maximum and minimum respectively, the latter being the typical “sports” ranking.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

order and sort.

Examples

(r1 <- rank(x1 <- c(3, 1, 4, 15, 92)))
x2 <- c(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5)
names(x2) <- letters[1:11]
(r2 <- rank(x2)) # ties are averaged

## rank() is "idempotent": rank(rank(x)) == rank(x) :
stopifnot(rank(r1) == r1, rank(r2) == r2)

## ranks without averaging
rank(x2, ties.method= "first")  # first occurrence wins
rank(x2, ties.method= "random") # ties broken at random
rank(x2, ties.method= "random") # and again

## keep ties ties, no average
(rma <- rank(x2, ties.method= "max"))  # as used classically
(rmi <- rank(x2, ties.method= "min"))  # as in Sports
stopifnot(rma + rmi == round(r2 + r2))


Recursively Apply a Function to a List

Description

rapply is a recursive version of lapply.

Usage

rapply(object, f, classes = "ANY", deflt = NULL,
       how = c("unlist", "replace", "list"), ...)

Arguments

object | A list.
f | A function of a single argument.
classes | A character vector of class names, or "ANY" to match any class.
deflt | The default result (not used if how = "replace").
how | A character string matching the three possibilities given: see Details.
... | additional arguments passed to the call to f.

Details

This function has two basic modes. If how = "replace", each element of the list which is not itself a list and has a class included in classes is replaced by the result of applying f to the element.

If the mode is how = "list" or how = "unlist", the list is copied, all non-list elements which have a class included in classes are replaced by the result of applying f to the element and all others are replaced by deflt. Finally, if how = "unlist", unlist(recursive = TRUE) is called on the result.

The semantics differ in detail from lapply: in particular the arguments are evaluated before calling the C code.

Value

If how = "unlist", a vector, otherwise a list of similar structure to object.

References

Chambers, J. A. (1998) Programming with Data. Springer.
(rapply is only described briefly there.)

See Also

lapply, dendrapply.

Examples

X <- list(list(a=pi, b=list(c=1:1)), d="a test")
rapply(X, function(x) x, how="replace")
rapply(X, sqrt, classes="numeric", how="replace")
rapply(X, nchar, classes="character", deflt = as.integer(NA), how="list")
rapply(X, nchar, classes="character", deflt = as.integer(NA), how="unlist")
rapply(X, nchar, classes="character", how="unlist")
rapply(X, log, classes="numeric", how="replace", base=2)


Raw Vectors

Description

Creates or tests for objects of type "raw".

Usage

raw(length = 0)
as.raw(x)

Arguments

length | desired length.
x | object to be coerced.

Details

The raw type is intended to hold raw bytes. It is possible to extract subsequences of bytes, and to replace elements (but only by elements of a raw vector). The relational operators (see Comparison) work, as do the logical operators (see Logic) with a bitwise interpretation.

A raw vector is printed with each byte separately represented as a pair of hex digits. If you want to see a character representation (with escape sequences for non-printing characters) use rawToChar.

Coercion to raw treats the input values as representing a small (decimal) integers, so the input is first coerced to integer, and then values which are outside the range [0 ... 255] or are NA are set to 0 (the nul byte).

Value

raw creates a raw vector of the specified length. Each element of the vector is equal to 0. Raw vectors are used to store fixed-length sequences of bytes.
as.raw attempts to coerce its argument to be of raw type. The (elementwise) answer will be 0 unless the coercion succeeds.

See Also

charToRaw, rawShift, etc.

Examples

xx <- raw(2)
xx[1] <- as.raw(40)     # NB, not just 40.
xx[2] <- charToRaw("A")
xx

x <- "A test string"
(y <- charToRaw(x))
is.vector(y) # TRUE
rawToChar(y)

isASCII <-  function(txt) all(charToRaw(txt) <= as.raw(127))
isASCII(x)  # true
isASCII("\x9c25.63") # false  (in Latin-1, this is an amount in UK pounds)


Convert to or from Raw Vectors

Description

Conversion and manipulation of objects of type "raw".

Usage

charToRaw(x)
rawToChar(x, multiple = FALSE)

rawShift(x, n)

rawToBits(x)
intToBits(x)
packBits(x, type = c("raw", "integer"))

Arguments

x | object to be converted or shifted.
multiple | logical: should the conversion be to a single character string or multiple individual characters?
n | the number of bits to shift. Positive numbers shift right and negative numbers shift left: allowed values are -8 ... 8.
type | the result type.

Details

packBits accepts raw, integer or logical inputs, the last two without any NAs.

Value

charToRaw converts a length-one character string to raw bytes.
rawToChar converts raw bytes either to a single character string or a character vector of single bytes. (Note that a single character string could contain embedded nuls.)
rawToBits returns a raw vector of 8 times the length of a raw vector with entries 0 or 1. intToBits returns a raw vector of 32 times the length of an integer vector with entries 0 or 1. In both cases the unpacking is least-significant bit first.
packbits packs its input (using only the lowest bit for raw or integer vectors) least-significant bit first to a raw or integer vector.

Examples

x <- "A test string"
(y <- charToRaw(x))
is.vector(y) # TRUE

rawToChar(y)
rawToChar(y, multiple = TRUE)
(xx <- c(y, as.raw(0), charToRaw("more")))
rawToChar(xx)
xxx <- xx
xxx[length(y)+1] <- charToRaw("&")
xxx
rawToChar(xxx)

rawShift(y, 1)
rawShift(y, -2)

rawToBits(y)


Utilities for Processing Rd Files

Description

Utilities for converting files in R documentation (Rd) format to other formats or create indices from them, and for converting documentation in other formats to Rd format.

Usage

R CMD Rdconv [options] file
R CMD Rd2dvi.sh [options] files
R CMD Rd2txt [options] file
R CMD Sd2Rd [options] file

Arguments

file | the path to a file to be processed.
files | a list of file names specifying the R documentation sources to use, by either giving the paths to the files, or the path to a directory with the sources of a package.
options | further options to control the processing, or for obtaining information about usage and version of the utility.

Details

Rdconv converts Rd format to other formats. Currently, plain text, HTML, LaTeX, S version 3 (Sd), and S version 4 (.sgml) formats are supported. It can also extract the examples for run-time testing.

Rd2dvi and Rd2txt are user-level programs for producing DVI/PDF output or pretty text output from Rd sources.

Sd2Rd converts S (version 3 or 4) documentation formats to Rd format.

Use R CMD foo --help to obtain usage information on utility foo.

Note

Conversion to S version 3/4 formats is rough: there are some .Rd constructs for which there is no natural analogue. They are intended as a starting point for hand-tuning.

See Also

The chapter “Processing Rd format” in “Writing R Extensions” (see the Manuals sub-menu of the Help menu on the console).


Data Input

Description

Reads a file in table format and creates a data frame from it, with cases corresponding to lines and variables to fields in the file.

Usage

read.table(file, header = FALSE, sep = "", quote = "\"'",
           dec = ".", row.names, col.names,
           as.is = !stringsAsFactors,
           na.strings = "NA", colClasses = NA, nrows = -1,
           skip = 0, check.names = TRUE, fill = !blank.lines.skip,
           strip.white = FALSE, blank.lines.skip = TRUE,
           comment.char = "#", allowEscapes = FALSE, flush = FALSE,
           stringsAsFactors = default.stringsAsFactors())

read.csv(file, header = TRUE, sep = ",", quote="\"", dec=".",
         fill = TRUE, comment.char="", ...)

read.csv2(file, header = TRUE, sep = ";", quote="\"", dec=",",
          fill = TRUE, comment.char="", ...)

read.delim(file, header = TRUE, sep = "\t", quote="\"", dec=".",
           fill = TRUE, comment.char="", ...)

read.delim2(file, header = TRUE, sep = "\t", quote="\"", dec=",",
            fill = TRUE, comment.char="", ...)

Arguments

file | the name of the file which the data are to be read from. Each row of the table appears as one line of the file. If it does not contain an absolute path, the file name is relative to the current working directory, getwd(). Tilde-expansion is performed where supported. Alternatively, file can be a connection, which will be opened if necessary, and if so closed at the end of the function call. (If stdin() is used, the prompts for lines may be somewhat confusing. Terminate input with a blank line or an EOF signal, Ctrl-D on Unix and Ctrl-Z on Windows. Any pushback on stdin() will be cleared before return.) file can also be a complete URL. To read a data file not in the current encoding (for example a Latin-1 file in a UTF-8 locale or conversely) use a file connection setting the encoding argument.
header | a logical value indicating whether the file contains the names of the variables as its first line. If missing, the value is determined from the file format: header is set to TRUE if and only if the first row contains one fewer field than the number of columns.
sep | the field separator character. Values on each line of the file are separated by this character. If sep = "" (the default for read.table) the separator is “white space”, that is one or more spaces, tabs, newlines or carriage returns.
quote | the set of quoting characters. To disable quoting altogether, use quote = "". See scan for the behaviour on quotes embedded in quotes.
dec | the character used in the file for decimal points.
row.names | a vector of row names. This can be a vector giving the actual row names, or a single number giving the column of the table which contains the row names, or character string giving the name of the table column containing the row names. If there is a header and the first row contains one fewer field than the number of columns, the first column in the input is used for the row names. Otherwise if row.names is missing, the rows are numbered. Using row.names = NULL forces row numbering.
col.names | a vector of optional names for the variables. The default is to use "V" followed by the column number.
as.is | the default behavior of read.table is to convert character variables (which are not converted to logical, numeric or complex) to factors. The variable as.is controls the conversion of columns not otherwise specified by colClasses. Its value is either a vector of logicals (values are recycled if necessary), or a vector of numeric or character indices which specify which columns should not be converted to factors. Note: to suppress all conversions including those of numeric columns, set colClasses = "character". Note that as.is is specified per column (not per variable) and so includes the column of row names (if any) and any columns to be skipped.
na.strings | a character vector of strings which are to be interpreted as NA values. Blank fields are also considered to be missing values in logical, integer, numeric and complex fields.
colClasses | character. A vector of classes to be assumed for the columns. Recycled as necessary, or if the character vector is named, unspecified values are taken to be NA. Possible values are NA (when type.convert is used), "NULL" (when the column is skipped), one of the atomic vector classes (logical, integer, numeric, complex, character, raw), or "factor", "Date" or "POSIXct". Otherwise there needs to be an as method (from package methods) for conversion from "character" to the specified formal class. Note that colClasses is specified per column (not per variable) and so includes the column of row names (if any).
nrows | the maximum number of rows to read in. Negative values are ignored.
skip | the number of lines of the data file to skip before beginning to read data.
check.names | logical. If TRUE then the names of the variables in the data frame are checked to ensure that they are syntactically valid variable names. If necessary they are adjusted (by make.names) so that they are, and also to ensure that there are no duplicates.
fill | logical. If TRUE then in case the rows have unequal length, blank fields are implicitly added. See Details.
strip.white | logical. Used only when sep has been specified, and allows the stripping of leading and trailing white space from character fields (numeric fields are always stripped). See scan for further details, remembering that the columns may include the row names.
blank.lines.skip | logical: if TRUE blank lines in the input are ignored.
comment.char | character: a character vector of length one containing a single character or an empty string. Use "" to turn off the interpretation of comments altogether.
allowEscapes | logical. Should C-style escapes such as \n be processed or read verbatim (the default)? Note that if not within quotes these could be interpreted as a delimiter (but not as a comment character). For more details see scan.
flush | logical: if TRUE, scan will flush to the end of the line after reading the last of the fields requested. This allows putting comments after the last field.
stringsAsFactors | logical: should character vectors be converted to factors?
... | Further arguments to read.table.

Details

A field or line is ‘blank’ if it contains nothing (except whitespace if no separator is specified) before a comment character or the end of the field or line.

If row.names is not specified and the header line has one less entry than the number of columns, the first column is taken to be the row names. This allows data frames to be read in from the format in which they are printed. If row.names is specified and does not refer to the first column, that column is discarded from such files.

The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

read.csv and read.csv2 are identical to read.table except for the defaults. They are intended for reading “comma separated value” files (‘.csv’) or (read.csv2) the variant used in countries that use a comma as decimal point and a semicolon as field separator. Similarly, read.delim and read.delim2 are for reading delimited files, defaulting to the TAB character for the delimiter. Notice that header = TRUE and fill = TRUE in these variants, and that the comment character is disabled.

The rest of the line after a comment character is skipped; quotes are not processed in comments. Complete comment lines are allowed provided blank.lines.skip = TRUE; however, comment lines prior to the header must have the comment character in the first non-blank column.

Quoted fields with embedded newlines are supported except after a comment character.

Value

A data frame (data.frame) containing a representation of the data in the file. Empty input is an error unless col.names is specified, when a 0-row data frame is returned: similarly giving just a header line if header = TRUE results in a 0-row data frame.
This function is the principal means of reading tabular data into R.

Note

The columns referred to in as.is and colClasses include the column of row names (if any).

Less memory will be used if colClasses is specified as one of the six atomic vector classes.

Using nrows, even as a mild over-estimate, will help memory usage.

Using comment.char = "" will be appreciably faster.

read.table is not the right tool for reading large matrices, especially those with many columns: it is designed to read data frames which may have columns of very different classes. Use scan instead.

Prior to version 1.9.0, underscores were not valid in variable names, and code that relies on them being converted to dots will no longer work. The simplest workaround is to use names(d) <- gsub("_", ".", names(d)), or, avoiding the (small) risk of creating duplicate names, names(d) <- make.names(gsub("_", ".", names(d)), unique=TRUE).

References

Chambers, J. M. (1992) Data for models. Chapter 3 of Statistical Models in S eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole.

See Also

The R Data Import/Export manual.

scan, type.convert, read.fwf for reading fixed width formatted input; write.table; data.frame.

count.fields can be useful to determine problems with reading files which result in reports of incorrect record lengths.


Transfer Binary Data To and From Connections

Description

Read binary data from a connection, or write binary data to a connection.

Usage

readBin(con, what, n = 1, size = NA, signed = TRUE,
        endian = .Platform$endian)

writeBin(object, con, size = NA, endian = .Platform$endian)

Arguments

con | A connection object or a character string naming a file or a raw vector.
what | Either an object whose mode will give the mode of the vector to be read, or a character vector of length one describing the mode: one of "numeric", "double", "integer", "int", "logical", "complex", "character", "raw".
n | integer. The (maximal) number of records to be read. You can use an over-estimate here, but not too large as storage is reserved for n items.
size | integer. The number of bytes per element in the byte stream. The default, NA, uses the natural size. Size changing is not supported for raw and complex vectors.
signed | logical. Only used for integers of sizes 1 and 2, when it determines if the quantity on file should be regarded as a signed or unsigned integer.
endian | The endian-ness ("big" or "little" of the target system for the file. Using "swap" will force swapping endian-ness.
object | An R object to be written to the connection.

Details

If con is a character string, the functions call file to obtain an file connection which is opened for the duration of the function call.

If the connection is open it is read/written from its current position. If it is not open, it is opened for the duration of the call and then closed again. The connection must be open or open-able in binary mode.

If readBin is called con with a raw vector, the data in the vector is used as input. If writeBin is called with con a raw vector, it is just an indication that a raw vector should be returned.

If size is specified and not the natural size of the object, each element of the vector is coerced to an appropriate type before being written or as it is read. Possible sizes are 1, 2, 4 and possibly 8 for integer or logical vectors, and 4, 8 and possibly 12/16 for numeric vectors. (Note that coercion occurs as signed types except if signed = FALSE when reading integers of sizes 1 and 2.) Changing sizes is unlikely to preserve NAs, and the extended precision sizes are unlikely to be portable across platforms.

readBin and writeBin read and write C-style zero-terminated character strings. Input strings are limited to 10000 characters. readChar and writeChar can be used to read and write fixed-length strings.

Handling R's missing and special (Inf, -Inf and NaN) values is discussed in the R Data Import/Export manual.

Value

For readBin, a vector of appropriate mode and length the number of items read (which might be less than n).
For writeBin, a raw vector (if con is a raw vector) or invisibly NULL.

Note

Integer read/writes of size 8 will be available if either C type long is of size 8 bytes or C type long long exists and is of size 8 bytes.

Real read/writes of size sizeof(long double) (usually 12 or 16 bytes) will be available only if that type is available and different from double.

If readBin(what = character()) is used incorrectly on a file which does not contain C-style character strings, warnings (usually many) are given. From a file or connection, the input will be broken into pieces of length 10000 with any final part being discarded.

See Also

The R Data Import/Export manual.

readChar to read/write fixed-length strings.

connections, readLines, writeLines.

.Machine for the sizes of long, long long and long double.

Examples

zz <- file("testbin", "wb")
writeBin(1:10, zz)
writeBin(pi, zz, endian="swap")
writeBin(pi, zz, size=4)
writeBin(pi^2, zz, size=4, endian="swap")
writeBin(pi+3i, zz)
writeBin("A test of a connection", zz)
z <- paste("A very long string", 1:100, collapse=" + ")
writeBin(z, zz)
if(.Machine$sizeof.long == 8 || .Machine$sizeof.longlong == 8)
    writeBin(as.integer(5^(1:10)), zz, size = 8)
if((s <-.Machine$sizeof.longdouble) > 8)
    writeBin((pi/3)^(1:10), zz, size = s)
close(zz)

zz <- file("testbin", "rb")
readBin(zz, integer(), 4)
readBin(zz, integer(), 6)
readBin(zz, numeric(), 1, endian="swap")
readBin(zz, numeric(), size=4)
readBin(zz, numeric(), size=4, endian="swap")
readBin(zz, complex(), 1)
readBin(zz, character(), 1)
z2 <- readBin(zz, character(), 1)
if(.Machine$sizeof.long == 8 || .Machine$sizeof.longlong == 8)
    readBin(zz, integer(), 10,  size = 8)
if((s <-.Machine$sizeof.longdouble) > 8)
    readBin(zz, numeric(), 10, size = s)
close(zz)
unlink("testbin")
stopifnot(z2 == z)

## signed vs unsigned ints
zz <- file("testbin", "wb")
x <- as.integer(seq(0, 255, 32))
writeBin(x, zz, size=1)
writeBin(x, zz, size=1)
x <- as.integer(seq(0, 60000, 10000))
writeBin(x, zz, size=2)
writeBin(x, zz, size=2)
close(zz)
zz <- file("testbin", "rb")
readBin(zz, integer(), 8, size=1)
readBin(zz, integer(), 8, size=1, signed=FALSE)
readBin(zz, integer(), 7, size=2)
readBin(zz, integer(), 7, size=2, signed=FALSE)
close(zz)
unlink("testbin")

## use of raw
z <- writeBin(pi^{1:5}, raw(), size = 4)
readBin(z, numeric(), 5, size = 4)
z <- writeBin(c("a", "test", "of", "character"), raw())
rawToChar(z)
readBin(z, character(), 4)


Transfer Character Strings To and From Connections

Description

Transfer character strings to and from connections, without assuming they are null-terminated on the connection.

Usage

readChar(con, nchars)

writeChar(object, con,
          nchars = nchar(object, type="chars"), eos = "")

Arguments

con | A connection object or a character string naming a file.
nchars | integer, giving the lengths in characters of (unterminated) character strings to be read or written. Must be >= 0 and not missing.
object | A character vector to be written to the connection, at least as long as nchars.
eos | ‘end of string’: character string . The terminator to be written after each string, followed by an ASCII nul; use NULL for no terminator at all.

Details

These functions complement readBin and writeBin which read and write C-style zero-terminated character strings. They are for strings of known length, and can optionally write an end-of-string mark. They are intended only for character strings valid in the current locale.

If con is a character string, the functions call file to obtain an file connection which is opened for the duration of the function call.

If the connection is open it is read/written from its current position. If it is not open, it is opened for the duration of the call and then closed again. Connections can be open in either text or binary mode.

In a single-byte locale, character strings containing ASCII nul(s) will be read correctly by readChar and appear with embedded nuls in the character vector returned. This may not work for multi-byte locales, and does not work for writeChar.

If the character length requested for readChar is longer than the data available on the connection, what is available is returned. For writeChar if too many characters are requested the output is zero-padded, with a warning.

Missing strings are written as NA.

Value

For readChar, a character vector of length the number of items read (which might be less than length(nchars)).
For writeChar none (strictly, invisible NULL).

See Also

The R Data Import/Export manual.

connections, readLines, writeLines, readBin

Examples

## test fixed-length strings
zz <- file("testchar", "wb")
x <- c("a", "this will be truncated", "abc")
nc <- c(3, 10, 3)
writeChar(x, zz, nc, eos=NULL)
writeChar(x, zz, eos="\r\n")
close(zz)

zz <- file("testchar", "rb")
readChar(zz, nc)
readChar(zz, nchar(x)+3) # need to read the terminator explicitly
close(zz)
unlink("testchar")


Read a Line from the Terminal

Description

readline reads a line from the terminal

Usage

readline(prompt = "")

Arguments

prompt the string printed when prompting the user for input. Should usually end with a space " ".

Details

The prompt string will be truncated to a maximum allowed length, normally 256 chars (but can be changed in the source code).

Value

A character vector of length one.

See Also

readLines for reading text lines of connections, including files.

Examples

fun <- function() {
  ANSWER <- readline("Are you a satisfied R user? ")
  if (substr(ANSWER, 1, 1) == "n")
    cat("This is impossible.  YOU LIED!\n")
  else
    cat("I knew it.\n")
}
fun()


Read Text Lines from a Connection

Description

Read text lines from a connection.

Usage

readLines(con = stdin(), n = -1, ok = TRUE, warn = TRUE)

Arguments

con | a connection object or a character string.
n | integer. The (maximal) number of lines to read. Negative values indicate that one should read up to the end of the connection.
ok | logical. Is it OK to reach the end of the connection before n > 0 lines are read? If not, an error will be generated.
warn | logical. Warn if a text file is missing a final EOL.

Details

If the con is a character string, the function calls file to obtain a file connection which is opened for the duration of the function call.

If the connection is open it is read from its current position. If it is not open, it is opened for the duration of the call and then closed again.

If the final line is incomplete (no final EOL marker) the behaviour depends on whether the connection is blocking or not. For a blocking text-mode connection (or a non-text-mode connection) the line will be accepted, with a warning. For a non-blocking text-mode connection the incomplete line is pushed back, silently.

Whatever mode the connection is opened in, any of LF, CRLF or CR will be accepted as the EOL marker for a line.

Value

A character vector of length the number of lines read.

See Also

connections, writeLines, readBin, scan

Examples

cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file="ex.data",
    sep="\n")
readLines("ex.data", n=-1)
unlink("ex.data") # tidy up

## difference in blocking
cat("123\nabc", file = "test1")
readLines("test1") # line with a warning

con <- file("test1", "r", blocking = FALSE)
readLines(con) # empty
cat(" def\n", file = "test1", append = TRUE)
readLines(con) # gets both
close(con)

unlink("test1") # tidy up


Real Vectors

Description

real creates a double precision vector of the specified length. Each element of the vector is equal to 0.

as.real attempts to coerce its argument to be of real type.

is.real returns TRUE or FALSE depending on whether its argument is of real type or not.

Usage

real(length = 0)
as.real(x, ...)
is.real(x)

Arguments

length | desired length.
x | object to be coerced or tested.
... | further arguments passed to or from other methods.

Note

R has no single precision data type. All real numbers are stored in double precision format.


Recursive Calling

Description

Recall is used as a placeholder for the name of the function in which it is called. It allows the definition of recursive functions which still work after being renamed, see example below.

Usage

Recall(...)

Arguments

... all the arguments to be passed.

Note

Recall will not work correctly when passed as a function argument, e.g. to the apply family of functions.

See Also

do.call and call.

local for another way to write anonymous recursive functions.

Examples

## A trivial (but inefficient!) example:
fib <- function(n) if(n<=2) {if(n>=0) 1 else 0} else Recall(n-1) + Recall(n-2)
fibonacci <- fib; rm(fib)
## renaming wouldn't work without Recall
fibonacci(10) # 55


Finalization of Objects

Description

Registers an R function to be called upon garbage collection of object or (optionally) at the end of an R session.

Usage

  reg.finalizer(e, f, onexit = FALSE)

Arguments

e | Object to finalize. Must be environment or external pointer.
f | Function to call on finalization. Must accept a single argument, which will be the object to finalize.
onexit | logical: should the finalizer be run if the object is still uncollected at the end of the R session?

Value

NULL.

Note

The purpose of this function is mainly to allow objects that refer to external items (a temporary file, say) to perform cleanup actions when they are no longer referenced from within R. This only makes sense for objects that are never copied on assignment, hence the restriction to environments and external pointers.

See Also

gc and Memory for garbage collection and memory management.

Examples

f <- function(e) print("cleaning....")
g <- function(x){ e <- environment(); reg.finalizer(e,f) }
g()
invisible(gc()) # trigger cleanup


Regular Expressions as used in R

Description

This help page documents the regular expression patterns supported by grep and related functions regexpr, gregexpr, sub and gsub, as well as by strsplit.

Details

A ‘regular expression’ is a pattern that describes a set of strings. Three types of regular expressions are used in R, extended regular expressions, used by grep(extended = TRUE) (its default), basic regular expressions, as used by grep(extended = FALSE), and Perl-like regular expressions used by grep(perl = TRUE).

Other functions which use regular expressions (often via the use of grep) include apropos, browseEnv, help.search, list.files, ls and strsplit. These will all use extended regular expressions, unless strsplit is called with argument extended = FALSE or perl = TRUE.

Patterns are described here as they would be printed by cat: do remember that backslashes need to be doubled in entering R character strings from the keyboard.

Extended Regular Expressions

This section covers the regular expressions allowed if extended = TRUE in grep, regexpr, gregexpr, sub, gsub and strsplit. They use the glibc 2.3.6 implementation of the POSIX 1003.2 standard.

Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions.

The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any metacharacter with special meaning may be quoted by preceding it with a backslash. The metacharacters are . \ | ( ) [ { ^ $ * + ?.

A character class is a list of characters enclosed by [ and ] which matches any single character in that list; if the first character of the list is the caret ^, then it matches any character not in the list. For example, the regular expression [0123456789] matches any single digit, and [^abc] matches anything except the characters a, b or c. A range of characters may be specified by giving the first and last characters, separated by a hyphen. (Because their interpretation is so system-dependent, they are best avoided.)

The precise way character ranges are interpreted depends on the values of perl and ignore.case. For basic and extended regular expressions the collation order is taken from the OS's implementation of the setting of the locale category LC_COLLATE, so [W-Z] may include x and if it does may or may not include w. (In most English locales the collation order is wWxXyYzZ.) For caseless matching the characters in a range are interpreted as if in lower case, so in an English locale [W-z] matches WXYZwxyz.

For Perl regexps, the ranges are interpreted in the numerical order of the characters, either as bytes in an 8-bit locale or as Unicode points in a UTF-8 locale.

Certain named classes of characters are predefined. Their interpretation depends on the locale (see locales); the interpretation below is that of the POSIX locale.

[:alnum:]
Alphanumeric characters: [:alpha:] and [:digit:].
[:alpha:]
Alphabetic characters: [:lower:] and [:upper:].
[:blank:]
Blank characters: space and tab.
[:cntrl:]
Control characters. In ASCII, these characters have octal codes 000 through 037, and 177 (DEL). In another character set, these are the equivalent characters, if any.
[:digit:]
Digits: 0 1 2 3 4 5 6 7 8 9.
[:graph:]
Graphical characters: [:alnum:] and [:punct:].
[:lower:]
Lower-case letters in the current locale.
[:print:]
Printable characters: [:alnum:], [:punct:] and space.
[:punct:]
Punctuation characters: ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~.
[:space:]
Space characters: tab, newline, vertical tab, form feed, carriage return, and space.
[:upper:]
Upper-case letters in the current locale.
[:xdigit:]
Hexadecimal digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F a b c d e f.

For example, [[:alnum:]] means [0-9A-Za-z], except the latter depends upon the locale and the character encoding, whereas the former is independent of locale and character set. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket list.) Most metacharacters lose their special meaning inside lists. To include a literal ], place it first in the list. Similarly, to include a literal ^, place it anywhere but first. Finally, to include a literal -, place it first or last. (Only these and \ remain special inside character classes.)

The period . matches any single character. The symbol \w is documented to be synonym for [[:alnum:]] and \W is its negation. However, \w also matches underscore in the GNU grep code used in R.

The caret ^ and the dollar sign $ are metacharacters that respectively match the empty string at the beginning and end of a line. The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it is not at the edge of a word.

A regular expression may be followed by one of several repetition quantifiers:

?
The preceding item is optional and will be matched at most once.
*
The preceding item will be matched zero or more times.
+
The preceding item will be matched one or more times.
{n}
The preceding item is matched exactly n times.
{n,}
The preceding item is matched n or more times.
{n,m}
The preceding item is matched at least n times, but not more than m times.

Repetition is greedy, so the maximal possible number of repeats is used.

Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated subexpressions.

Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either subexpression. For example, abba|cde matches either the string abba or the string cde. Note that alternation does not work inside character classes, where | has its literal meaning.

Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole subexpression may be enclosed in parentheses to override these precedence rules.

The backreference \N, where N is a single digit, matches the substring previously matched by the Nth parenthesized subexpression of the regular expression.

Basic Regular Expressions

This section covers the regular expressions allowed if extended = FALSE in grep, regexpr, gregexpr, sub, gsub and strsplit.

In basic regular expressions the metacharacters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \ {, \|, \(, and \). Thus the metacharacters are . \ [ ^ $ *.

Perl Regular Expressions

The perl = TRUE argument to grep, regexpr, gregexpr, sub, gsub and strsplit switches to the PCRE library that ‘implements regular expression pattern matching using the same syntax and semantics as Perl 5.6 or later, with just a few differences’.

For complete details please consult the man pages for PCRE, especially man pcrepattern and man pcreapi) on your system or from the sources at ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/. If PCRE support was compiled from the sources within R, the PCRE version is 6.7 as described here (version >= 4.0 is required if R is configured to use the system's PCRE library).

All the regular expressions described for extended regular expressions are accepted except \< and \>: in Perl all backslashed metacharacters are alphanumeric and backslashed symbols always are interpreted as a literal character. { is not special if it would be the start of an invalid interval specification. There can be more than 9 backreferences.

The construct (?...) is used for Perl extensions in a variety of ways depending on what immediately follows the ?.

Perl-like matching can work in several modes, set by the options (?i) (caseless, equivalent to Perl's /i), (?m) (multiline, equivalent to Perl's /m), (?s) (single line, so a dot matches all characters, even new lines: equivalent to Perl's /s) and (?x) (extended, whitespace data characters are ignored unless escaped and comments are allowed: equivalent to Perl's /x). These can be concatenated, so for example, (?im) sets caseless multiline matching. It is also possible to unset these options by preceding the letter with a hyphen, and to combine setting and unsetting such as (?im-sx). These settings can be applied within patterns, and then apply to the remainder of the pattern. Additional options not in Perl include (?U) to set ‘ungreedy’ mode (so matching is minimal unless ? is used, when it is greedy). Initially none of these options are set.

If you want to remove the special meaning from a sequence of characters, you can do so by putting them between \Q and \E. This is different from Perl in that $ and @ are handled as literals in \Q...\E sequences in PCRE, whereas in Perl, $ and @ cause variable interpolation.

The escape sequences \d, \s and \w represent any decimal digit, space character and ‘word’ character (letter, digit or underscore in the current locale) respectively, and their upper-case versions represent their negation. Unlike POSIX and earlier versions of Perl and PCRE, vertical tab is not regarded as a whitespace character.

Escape sequence \a is BEL, \e is ESC, \f is FF, \n is LF, \r is CR and \t is TAB. In addition \cx is cntrl-x for any x, \ddd is the octal character ddd (for up to three digits unless interpretable as a backreference), and \xhh specifies a character in hex.

Outside a character class, \b matches a word boundary, \B is its negation, \A matches at start of a subject (even in multiline mode, unlike ^), \Z matches at end of a subject or before newline at end, \z matches at end of a subject. and \G matches at first matching position in a subject. \C matches a single byte. including a newline.

The same repetition quantifiers as extended POSIX are supported. However, if a quantifier is followed by ?, the match is ‘ungreedy’, that is as short as possible rather than as long as possible (unless the meanings are reversed by the (?U) option.)

The sequence (?# marks the start of a comment which continues up to the next closing parenthesis. Nested parentheses are not permitted. The characters that make up a comment play no part at all in the pattern matching.

If the extended option is set, an unescaped # character outside a character class introduces a comment that continues up to the next newline character in the pattern.

The pattern (?:...) groups characters just as parentheses do but does not make a backreference.

Patterns (?=...) and (?!...) are zero-width positive and negative lookahead assertions: they match if an attempt to match the ... forward from the current position would succeed (or not), but use up no characters in the string being processed. Patterns (?<=...) and (?<!...) are the lookbehind equivalents: they do not allow repetition quantifiers nor \C in ....

Named subpatterns, atomic grouping, possessive qualifiers and conditional and recursive patterns are not covered here.

Author(s)

This help page is based on the documentation of GNU grep 2.4.2 and the pcrepattern man page from PCRE 6.7.

See Also

grep, apropos, browseEnv, glob2rx, help.search, list.files, ls and strsplit.

http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html


Replicate Elements of Vectors and Lists

Description

rep replicates the values in x. It is a generic function, and the (internal) default method is described here.

rep.int is a faster simplified version for the commonest case.

Usage

rep(x, ...)

rep.int(x, times)

Arguments

x | a vector (of any mode including a list) or a pairlist or a factor or (except for rep.int) a POSIXct or POSIXlt or date object.
... further arguments to be passed to or from other methods. For the internal default method these can include:
times
A vector giving the number of times to repeat each element if of length length(x), or to repeat the whole vector if of length 1.
length.out
non-negative integer. The desired length of the output vector. Ignored if NA or invalid.
each
non-negative integer. Each element of x is repeated each times. Treated as 1 if NA or invalid.
times | see ....

Details

The default behaviour is as if the call was rep(x, times=1, length.out=NA, each=1). Normally just one of the additional arguments is specified, but if code{each} is specified with either of the other two, its replication is performed first, and then that implied by times or length.out.

If times consists of a single integer, the result consists of the whole input repeated this many times. If times is a vector of the same length as x (after replication by each), the result consists of x[1] repeated times[1] times, x[2] repeated times[2] times and so on.

length.out may be given in place of times, in which case x is repeated as many times as is necessary to create a vector of this length. If both are given, length.out takes priority and times is ignored.

Non-integer values of times will be truncated towards zero. If times is a computed quantity it is prudent to add a small fuzz.

If x has length zero and length.out is supplied and is positive, the values are filled in using the extraction rules, that is by an NA of the appropriate class for an atomic vector (0 for raw vectors) and NULL for a list.

Value

An object of the same type as x (except that rep will coerce pairlists to vector lists).
rep.int returns no attributes.
The default method of rep gives the result names (which will almost always contain duplicates) if x had names, but retains no other attributes except for factors.

Note

Function rep.int is a simple case handled by internal code, and provided as a separate function purely for S compatibility.

As from R 2.4.0, function rep is a primitive, but (partial) matching of argument names is performed as for normal functions. You can no longer pass a missing argument to. e.g. length.out.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

seq, sequence.

Examples

rep(1:4, 2)
rep(1:4, each = 2)       # not the same.
rep(1:4, c(2,2,2,2))     # same as second.
rep(1:4, c(2,1,2,1))
rep(1:4, each = 2, len = 4)    # first 4 only.
rep(1:4, each = 2, len = 10)   # 8 integers plus two recycled 1's.
rep(1:4, each = 2, times = 3)  # length 24, 3 complete replications

rep(1, 40*(1-.8)) # length 7 on most platforms
rep(1, 40*(1-.8)+1e-7) # better

## replicate a list
fred <- list(happy = 1:10, name = "squash")
rep(fred, 5)

# date-time objects
x <- .leap.seconds[1:3]
rep(x, 2)
rep(as.POSIXlt(x), rep(2, 3))

## named factor
x <- factor(LETTERS[1:4]); names(x) <- letters[1:4]
x
rep(x, 2)
rep(x, each=2)
rep.int(x, 2)  # no names


Replace Values in a Vector

Description

replace replaces the values in x with indexes given in list by those given in values. If necessary, the values in values are recycled.

Usage

replace(x, list, values)

Arguments

x | vector
list | an index vector
values | replacement values

Value

A vector with the values replaced.

Note

x is unchanged: remember to assign the result.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.


Reverse Elements

Description

rev provides a reversed version of its argument. It is generic function with a default method for vectors and one for dendrograms.

Note that this is no longer needed (nor efficient) for obtaining vectors sorted into descending order, since that is now rather more directly achievable by sort(x, decreasing = TRUE).

Usage

rev(x)

Arguments

x a vector or another object for which reversal is defined.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

seq, sort.

Examples

x <- c(1:5,5:3)
## sort into descending order; first more efficiently:
stopifnot(sort(x, decreasing = TRUE) == rev(sort(x)))
stopifnot(rev(1:7) == 7:1)#- don't need 'rev' here


Return the R Home Directory

Description

Return the R home directory.

Usage

R.home(component="home")

Arguments

component As well as "home" which gives the R home directory, other known values are "bin", "doc", "etc" and "share" giving the paths to the corresponding parts of an R installation.

Details

The R home directory is the top-level directory of the R installation being run.

The R home directory is often referred to as R_HOME, and is the value of an environment variable of that name in an R session.

Value

A character string giving the R home directory or path to a particular component. Normally the components are all subdirectories of the R home directory, but this may not be the case in a Unix-like installation.


Run Length Encoding

Description

Compute the lengths and values of runs of equal values in a vector – or the reverse operation.

Usage

rle(x)
inverse.rle(x, ...)

Arguments

x | a simple vector for rle() or an object of class "rle" for inverse.rle().
... | further arguments which are ignored in R.

Value

rle() returns an object of class "rle" which is a list with components

lengths | an integer vector containing the length of each run.
values | a vector of the same length as lengths with the corresponding values.

inverse.rle() is the inverse function of rle().

Examples

x <- rev(rep(6:10, 1:5))
rle(x)
## lengths [1:5]  5 4 3 2 1
## values  [1:5] 10 9 8 7 6

z <- c(TRUE,TRUE,FALSE,FALSE,TRUE,FALSE,TRUE,TRUE,TRUE)
rle(z)
rle(as.character(z))

stopifnot(x == inverse.rle(rle(x)),
          z == inverse.rle(rle(z)))


Remove Objects from a Specified Environment

Description

remove and rm can be used to remove objects. These can be specified successively as character strings, or in the character vector list, or through a combination of both. All objects thus specified will be removed.

If envir is NULL then the currently active environment is searched first.

If inherits is TRUE then parents of the supplied directory are searched until a variable with the given name is encountered. A warning is printed for each variable that is not found.

Usage

remove(..., list = character(0), pos = -1,
       envir = as.environment(pos), inherits = FALSE)

rm    (..., list = character(0), pos = -1,
       envir = as.environment(pos), inherits = FALSE)

Arguments

... | the objects to be removed, as names (unquoted) or character strings (quoted).
list | a character vector naming objects to be removed.
pos | where to do the removal. By default, uses the current environment. See the details for other possibilities.
envir | the environment to use. See the details section.
inherits | should the enclosing frames of the environment be inspected?

Details

The pos argument can specify the environment from which to remove the objects in any of several ways: as an integer (the position in the search list); as the character string name of an element in the search list; or as an environment (including using sys.frame to access the currently active function calls). The envir argument is an alternative way to specify an environment, but is primarily there for back compatibility.

It is not allowed to remove variables from the base environment and base namespace, nor from any environment which is locked (see lockEnvironment).

Earlier versions of R incorrectly claimed that supplying a character vector in ... removed the objects named in the character vector, but it removed the character vector. Use the list argument to specify objects via a character vector.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

ls, objects

Examples

tmp <- 1:4
## work with tmp  and cleanup
rm(tmp)

## Not run:
## remove (almost) everything in the working environment.
## You will get no warning, so don't do this unless you are really sure.
rm(list = ls())
## End(Not run)


Rounding of Numbers

Description

ceiling takes a single numeric argument x and returns a numeric vector containing the smallest integers not less than the corresponding elements of x.

floor takes a single numeric argument x and returns a numeric vector containing the largest integers not greater than the corresponding elements of x.

trunc takes a single numeric argument x and returns a numeric vector containing the integers formed by truncating the values in x toward 0.

round rounds the values in its first argument to the specified number of decimal places (default 0).

signif rounds the values in its first argument to the specified number of significant digits.

zapsmall determines a digits argument dr for calling round(x, digits = dr) such that values “close to zero” (compared with the maximal absolute value) are “zapped”, i.e., treated as 0.

Usage

ceiling(x)
floor(x)
trunc(x)

round(x, digits = 0)
signif(x, digits = 6)
zapsmall(x, digits = getOption("digits"))

Arguments

x | a numeric vector. A complex vector is allowed for round, signif and zapsmall.
digits | integer indicating the precision to be used.

Details

All but zapsmall are generic functions: methods can be defined for them individually or via the Math group generic.

Note that for rounding off a 5, the IEC 60559 standard is expected to be used, “go to the even digit”. Therefore round(0.5) is 0 and round(-1.5) is -2. However, this is dependent on OS services and on representation error (since e.g. 0.15 is not represented exactly, the rounding rule applies to the represented number and not to the printed number, and so round(0.15, 1) could be either 0.1 or 0.2).

For signif the recognized values of digits are 1...22. Complex numbers are rounded to retain the specified number of digits in the larger of the components. Each element of the vector is rounded individually, unlike printing.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole. (Except zapsmall.)

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language. Springer. (zapsmall.)

See Also

as.integer.

Examples

round(.5 + -2:4) # IEEE rounding: -2  0  0  2  2  4  4
( x1 <- seq(-2, 4, by = .5) )
round(x1)#-- IEEE rounding !
x1[trunc(x1) != floor(x1)]
x1[round(x1) != floor(x1 + .5)]
(non.int <- ceiling(x1) != floor(x1))

x2 <- pi * 100^(-1:3)
round(x2, 3)
signif(x2, 3)

print   (x2 / 1000, digits=4)
zapsmall(x2 / 1000, digits=4)
zapsmall(exp(1i*0:4*pi/2))


Round / Truncate Data-Time Objects

Description

Round or truncate date-time objects.

Usage

## S3 method for class 'POSIXt':
round(x, units = c("secs", "mins", "hours", "days"))
## S3 method for class 'POSIXt':
trunc(x, units = c("secs", "mins", "hours", "days"))

## S3 method for class 'Date':
round(x, ...)
## S3 method for class 'Date':
trunc(x)

Arguments

x | an object inheriting from "POSIXt" or "Date".
units | one of the units listed. Can be abbreviated.
... | arguments to be passed to or from other methods, notably digits.

Details

The time is rounded or truncated to the second, minute, hour or day. Timezones are only relevant to days, when midnight in the current timezone is used.

The methods for class "Date" are of little use except to remove fractional days.

Value

An object of class "POSIXlt".

See Also

round for the generic function and default methods.

DateTimeClasses, Date

Examples

round(.leap.seconds + 1000, "hour")
trunc(Sys.time(), "day")


Row Indexes

Description

Returns a matrix of integers indicating their row number in the matrix.

Usage

row(x, as.factor = FALSE)

Arguments

x | a matrix.
as.factor | a logical value indicating whether the value should be returned as a factor rather than as numeric.

Value

An integer matrix with the same dimensions as x and whose ij-th element is equal to i.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

col to get columns.

Examples

x <- matrix(1:12, 3, 4)
# extract the diagonal of a matrix
dx <- x[row(x) == col(x)]
dx

# create an identity 5-by-5 matrix
x <- matrix(0, nr = 5, nc = 5)
x[row(x) == col(x)] <- 1
x


Get and Set Row Names for Data Frames

Description

All data frames have a row names attribute, a character vector of length the number of rows with no duplicates nor missing values.

For convenience, these are generic functions for which users can write other methods, and there are default methods for arrays. The description here is for the data.frame method.

Usage

row.names(x)
row.names(x) <- value

Arguments

x | object of class "data.frame", or any other class for which a method has been defined.
value | an object to be coerced to character unless an integer vector. It should have (after coercion) the same length as the number of rows of x with no duplicated nor missing values. NULL is also allowed: see Details.

Details

A data frame has (by definition) a vector of row names which has length the number of rows in the data frame, and contains neither missing nor duplicated values.

Prior to R 2.4.0, row names were character. As from R 2.4.0, they are allowed to be integer or character, but for backwards compatibility row.names will always return a character vector. (Use attr(x, "row.names") if you need the actual value.)

Using NULL for the value resets the row names to seq_len(nrow(x)).

Value

row.names returns a character vector.
row.names<- returns a data frame with the row names changed.

Note

row.names is similar to rownames for arrays, and it has a method that calls rownames for an array argument.

Row names of the form 1:n for n > 2 are stored internally in a compact form, which might be seen from C code or by deparsing but never via row.names or attr(x, "row.names").

References

Chambers, J. M. (1992) Data for models. Chapter 3 of Statistical Models in S eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole.

See Also

data.frame, rownames, names.


Give column sums of a matrix or data frame, based on a grouping variable

rowsum(base) R Documentation

Give column sums of a matrix or data frame based on a grouping variable

Description

Compute column sums across rows of a matrix-like object for each level of a grouping variable. rowsum is generic, with a method for data frames and a default method for vectors and matrices.

Usage

rowsum(x, group, reorder = TRUE, ...)

## S3 method for class 'data.frame':
rowsum(x, group, reorder = TRUE, na.rm = FALSE, ...)

## Default S3 method:
rowsum(x, group, reorder = TRUE, na.rm = FALSE, ...)

Arguments

x | a matrix, data frame or vector of numeric data. Missing values are allowed. A numeric vector will be treated as a column vector.
group | a vector or factor giving the grouping, with one element per row of x. Missing values will be treated as another group and a warning will be given.
reorder | if TRUE, then the result will be in order of sort(unique(group)), if FALSE, it will be in the order that groups were encountered.
na.rm | logical (TRUE or FALSE). Should NA values be discarded?
... | other arguments to be passed to or from methods

Details

The default is to reorder the rows to agree with tapply as in the example below. Reordering should not add noticeably to the time except when there are very many distinct values of group and x has few columns.

The original function was written by Terry Therneau, but this is a new implementation using hashing that is much faster for large matrices.

To sum over all the rows of a matrix (ie, a single group) use colSums, which should be even faster.

Value

A matrix or data frame containing the sums. There will be one row per unique value of group.

See Also

tapply, aggregate, rowSums

Examples

x <- matrix(runif(100), ncol=5)
group <- sample(1:8, 20, TRUE)
(xsum <- rowsum(x, group))
## Slower versions
tapply(x, list(group[row(x)], col(x)), sum)
t(sapply(split(as.data.frame(x), group), colSums))
aggregate(x, list(group), sum)[-1]


Random Samples and Permutations

Description

sample takes a sample of the specified size from the elements of x using either with or without replacement.

Usage

sample(x, size, replace = FALSE, prob = NULL)

Arguments

x | Either a (numeric, complex, character or logical) vector of more than one element from which to choose, or a positive integer.
size | non-negative integer giving the number of items to choose.
replace | Should sampling be with replacement?
prob | A vector of probability weights for obtaining the elements of the vector being sampled.

Details

If x has length 1 and x >= 1, sampling takes place from 1:x. Note that this convenience feature may lead to undesired behaviour when x is of varying length sample(x). See the resample() example below.

By default size is equal to length(x) so that sample(x) generates a random permutation of the elements of x (or 1:x).

The optional prob argument can be used to give a vector of weights for obtaining the elements of the vector being sampled. They need not sum to one, but they should be nonnegative and not all zero. If replace is true, Walker's alias method (Ripley, 1987) is used when there are more that 250 reasonably probable values: this gives results incompatible with those from R < 2.2.0, and there will be a warning the first time this happens in a session.

If replace is false, these probabilities are applied sequentially, that is the probability of choosing the next item is proportional to the probabilities amongst the remaining items. The number of nonzero weights must be at least size in this case.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Ripley, B. D. (1987) Stochastic Simulation. Wiley.

Examples

x <- 1:12
# a random permutation
sample(x)
# bootstrap sampling -- only if length(x) > 1 !
sample(x,replace=TRUE)

# 100 Bernoulli trials
sample(c(0,1), 100, replace = TRUE)

## More careful bootstrapping --  Consider this when using sample()
## programmatically (i.e., in your function or simulation)!

# sample()'s surprise -- example
x <- 1:10
    sample(x[x >  8]) # length 2
    sample(x[x >  9]) # oops -- length 10!
try(sample(x[x > 10]))# error!

## This is safer, but only for sampling without replacement
resample <- function(x, size, ...)
  if(length(x) <= 1) { if(!missing(size) && size == 0) x[FALSE] else x
  } else sample(x, size, ...)

resample(x[x >  8])# length 2
resample(x[x >  9])# length 1
resample(x[x > 10])# length 0


Save R Objects

Description

save writes an external representation of R objects to the specified file. The objects can be read back from the file at a later date by using the function load (or data in some cases).

save.image() is just a short-cut for “save my current workspace”, i.e., save(list = ls(all=TRUE), file = ".RData"). It is also what happens with q("yes").

Usage

save(..., list = character(0),
     file = stop("'file' must be specified"),
     ascii = FALSE, version = NULL, envir = parent.frame(),
     compress = !ascii, eval.promises = TRUE)

save.image(file = ".RData", version = NULL, ascii = FALSE,
           compress = !ascii, safe = TRUE)

Arguments

... | the names of the objects to be saved.
list | A character vector containing the names of objects to be saved.
file | a connection or the name of the file where the data will be saved. Must be a file name for workspace format version 1.
ascii | if TRUE, an ASCII representation of the data is written. The default value of ascii is FALSE which leads to a more compact binary file being written.
version | the workspace format version to use. NULL specifies the current default format. The version used from R 0.99.0 to R 1.3.1 was version 1. The default format as from R 1.4.0 is version 2.
envir | environment to search for objects to be saved.
compress | logical specifying whether saving to a named file is to use compression. Ignored when file is a connection and for workspace format version 1.
eval.promises | logical: should objects which are promises be forced before saving?
safe | logical. If TRUE, a temporary file is used for creating the saved workspace. The temporary file is renamed to file if the save succeeds. This preserves an existing workspace file if the save fails, but at the cost of using extra disk space during the save.

Details

The names of the objects specified either as symbols in ... or as a character vector in list are used to look up the objects from environment envir. By default promises are evaluated, but if eval.promises = FALSE promises are saved (together with their evaluation environments). (Promises embedded in objects are always saved unevaluated.)

All R platforms use the XDR representation of binary objects in binary save-d files, and these are portable across all R platforms. (ASCII saves used to be useful for moving data between platforms but are now only of historical interest.)

Default values for the ascii, compress, safe and version arguments can be modified with the save.defaults option (used both by save and save.image), see also the example section below. If a save.image.defaults option is set it overrides save.defaults for function save.image (which allows this to have different defaults).

It is possible to compress later (with gzip) a file saved with compress = FALSE: the effect is the same as saving with compress = TRUE.

Warnings

The ... arguments only give the names of the objects to be saved: they are searched for in the environment given by the envir argument, and the actual objects given as arguments need not be those found.

Saved R objects are binary files, even those saved with ascii = TRUE, so ensure that they are transferred without conversion of end of line markers and of 8-bit characters. The lines are delimited by LF on all platforms.

Although the default version has not changed since R 1.4.0, this does not mean that saved files are necessarily backwards compatible. You will be able to load a saved image into an earlier version of R unless use is made of later additions (for example, raw vectors or external pointers).

Note

The defaults were changed to use compressed saves for save in 2.3.0 and for save.image in 2.4.0. Any recent version of R can read compressed save files, and a compressed file can be uncompressed (by gzip -d) for use with very old versions of R.

See Also

dput, dump, load, data.

Examples

x <- runif(20)
y <- list(a = 1, b = TRUE, c = "oops")
save(x, y, file = "xy.Rdata")
save.image()
unlink("xy.Rdata")
unlink(".RData")

# set save defaults using option:
options(save.defaults=list(ascii=TRUE, safe=FALSE))
save.image()
unlink(".RData")


Scaling and Centering of Matrix-like Objects

Description

scale is generic function whose default method centers and/or scales the columns of a numeric matrix.

Usage

scale(x, center = TRUE, scale = TRUE)

Arguments

x | a numeric matrix(like object).
center | either a logical value or a numeric vector of length equal to the number of columns of x.
scale | either a logical value or a numeric vector of length equal to the number of columns of x.

Details

The value of center determines how column centering is performed. If center is a numeric vector with length equal to the number of columns of x, then each column of x has the corresponding value from center subtracted from it. If center is TRUE then centering is done by subtracting the column means (omitting NAs) of x from their corresponding columns, and if center is FALSE, no centering is done.

The value of scale determines how column scaling is performed (after centering). If scale is a numeric vector with length equal to the number of columns of x, then each column of x is divided by the corresponding value from scale. If scale is TRUE then scaling is done by dividing the (centered) columns of x by their root-mean-square, and if scale is FALSE, no scaling is done.

The root-mean-square for a column is obtained by computing the square-root of the sum-of-squares of the non-missing values in the column divided by the number of non-missing values minus one.

Value

For scale.default, the centered, scaled matrix. The numeric centering and scalings used (if any) are returned as attributes "scaled:center" and "scaled:scale"

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

sweep which allows centering (and scaling) with arbitrary statistics.

For working with the scale of a plot, see par.

Examples

require(stats)
x <- matrix(1:10, nc=2)
(centered.x <- scale(x, scale=FALSE))
cov(centered.scaled.x <- scale(x))# all 1


Read Data Values

Description

Read data into a vector or list from the console or file.

Usage

scan(file = "", what = double(0), nmax = -1, n = -1, sep = "",
     quote = if(identical(sep, "\n")) "" else "'\"", dec = ".",
     skip = 0, nlines = 0, na.strings = "NA",
     flush = FALSE, fill = FALSE, strip.white = FALSE,
     quiet = FALSE, blank.lines.skip = TRUE, multi.line = TRUE,
     comment.char = "", allowEscapes = FALSE)

Arguments

file | the name of a file to read data values from. If the specified file is "", then input is taken from the keyboard (or stdin if input is redirected). (In this case input can be terminated by a blank line or an EOF signal, Ctrl-D on Unix and Ctrl-Z on Windows.) Otherwise, the file name is interpreted relative to the current working directory (given by getwd()), unless it specifies an absolute path. Tilde-expansion is performed where supported. Alternatively, file can be a connection, which will be opened if necessary, and if so closed at the end of the function call. Whatever mode the connection is opened in, any of LF, CRLF or CR will be accepted as the EOL marker for a line and so will match sep = "\n". file can also be a complete URL. To read a data file not in the current encoding (for example a Latin-1 file in a UTF-8 locale or conversely) use a file connection setting the encoding argument.
what | the type of what gives the type of data to be read. The supported types are logical, integer, numeric, complex, character, raw and list. If what is a list, it is assumed that the lines of the data file are records each containing length(what) items (“fields”) and the list components should have elements which are one of the first six types listed or NULL, see section ‘Details’ below.
nmax | the maximum number of data values to be read, or if what is a list, the maximum number of records to be read. If omitted or not positive (and nlines is not set to a positive value), scan will read to the end of file.
n | the maximum number of data values to be read, defaulting to no limit.
sep | by default, scan expects to read white-space delimited input fields. Alternatively, sep can be used to specify a character which delimits fields. A field is always delimited by an end-of-line marker unless it is quoted. If specified this should be the empty character string (the default) or NULL or a character string containing just one single-byte character.
quote | the set of quoting characters as a single character string or NULL. In a multibyte locale the quoting characters must be ASCII (single-byte).
dec | decimal point character. This should be a character string containing just one single-byte character. (NULL and a zero-length character vector are also accepted, and taken as the default.)
skip | the number of lines of the input file to skip before beginning to read data values.
nlines | if positive, the maximum number of lines of data to be read.
na.strings | character vector. Elements of this vector are to be interpreted as missing (NA) values. Blank fields are also considered to be missing values in logical, integer, numeric and complex fields.
flush | logical: if TRUE, scan will flush to the end of the line after reading the last of the fields requested. This allows putting comments after the last field, but precludes putting more that one record on a line.
fill | logical: if TRUE, scan will implicitly add empty fields to any lines with fewer fields than implied by what.
strip.white | vector of logical value(s) corresponding to items in the what argument. It is used only when sep has been specified, and allows the stripping of leading and trailing white space from character fields (numeric fields are always stripped). If strip.white is of length 1, it applies to all fields; otherwise, if strip.white[i] is TRUE and the i-th field is of mode character (because what[i] is) then the leading and trailing white space from field i is stripped.
quiet | logical: if FALSE (default), scan() will print a line, saying how many items have been read.
blank.lines.skip | logical: if TRUE blank lines in the input are ignored, except when counting skip and nlines.
multi.line | logical. Only used if what is a list. If FALSE, all of a record must appear on one line (but more than one record can appear on a single line). Note that using fill = TRUE implies that a record will terminated at the end of a line.
comment.char | character: a character vector of length one containing a single character or an empty string. Use "" to turn off the interpretation of comments altogether (the default).
allowEscapes | logical. Should C-style escapes such as \n be processed (the default) or read verbatim? Note that if not within quotes these could be interpreted as a delimiter (but not as a comment character). The escapes which are interpreted are the control characters \a, \b, \f, \n, \r, \t, \v and octal and hexadecimal representatons like \040 and \0x2A. Any other escaped character is treated as itself, including backslash.

Details

The value of what can be a list of types, in which case scan returns a list of vectors with the types given by the types of the elements in what. This provides a way of reading columnar data. If any of the types is NULL, the corresponding field is skipped (but a NULL component appears in the result).

The type of what or its components can be one of the six atomic vector types or NULL (see is.atomic).

‘White space’ is defined for the purposes of this function as one or more contiguous characters from the set space, horizontal tab, carriage return and line feed. It does not include form feed, vertical tab or other non-ASCII space characters.

Empty numeric fields are always regarded as missing values. Empty character fields are scanned as empty character vectors, unless na.strings contains "" when they are regarded as missing values.

If sep is the default (""), the character \ in a quoted string escapes the following character, so quotes may be included in the string by escaping them.

If sep is non-default, the fields may be quoted in the style of ‘.csv’ files where separators inside quotes ('' or "") are ignored and quotes may be put inside strings by doubling them. However, if sep = "\n" it is assumed by default that one wants to read entire lines verbatim.

Quoting is only interpreted in character fields and in NULL fields (which might be skipping character fields).

Note that since sep is a separator and not a terminator, reading a file by scan("foo", sep="\n", blank.lines.skip=FALSE) will give an empty final line if the file ends in a linefeed and not if it does not. This might not be what you expected; see also readLines.

If comment.char occurs (except inside a quoted character field), it signals that the rest of the line should be regarded as a comment and be discarded. Lines beginning with a comment character (possibly after white space with the default separator) are treated as blank lines.

scan attempts to share storage with character strings that have already been read in the call. If an upper bound on the number of character strings cannot be deduced from nmax or n, sharing is used for the first 10000 unique strings which are read in.

There is a check for a user interrupt every 1000 lines if what is a list, otherwise every 10000 items.

Value

if what is a list, a list of the same length and same names (as any) as what.
Otherwise, a vector of the type of what.

Note

The default for multi.line differs from S. To read one record per line, use flush = TRUE and multi.line = FALSE. (Note that quoted character strings can still include embedded new lines.)

If number of items is not specified, the internal mechanism re-allocates memory in powers of two and so could use up to three times as much memory as needed. (It needs both old and new copies.) If you can, specify either n or nmax whenever inputting a large vector, and nmax or nlines when inputting a large list.

Using scan on an open connection to read partial lines can lose chars: use an explicit separator to avoid this.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

read.table for more user-friendly reading of data matrices; readLines to read a file a line at a time. write.

Quotes for the details of C-style escape sequences.

readChar and readBin to read fixed or variable length character strings or binary representations of numbers a few at a time from a connection.

Examples

cat("TITLE extra line", "2 3 5 7", "11 13 17", file="ex.data", sep="\n")
pp <- scan("ex.data", skip = 1, quiet= TRUE)
    scan("ex.data", skip = 1)
    scan("ex.data", skip = 1, nlines=1)# only 1 line after the skipped one
scan("ex.data", what = list("","","")) # flush is F -> read "7"
scan("ex.data", what = list("","",""), flush = TRUE)
unlink("ex.data") # tidy up


Give Search Path for R Objects

Description

Gives a list of attached packages (see library), and R objects, usually data.frames.

Usage

search()
searchpaths()

Value

A character vector, starting with ".GlobalEnv", and ending with "package:base" which is R's base package required always.
searchpaths gives a similar character vector, with the entries for packages being the path to the package used to load the code.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole. (search.)

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language. Springer. (searchPaths.)

See Also

.packages to list just the packages on search path.

loadedNamespaces to list loaded namespaces.

attach and detach to change the search “path”, objects to find R objects in there.

Examples

search()
searchpaths()


Functions to Reposition Connections

Description

Functions to re-position connections.

Usage

seek(con, ...)
## S3 method for class 'connection':
seek(con, where = NA, origin = "start", rw = "", ...)

isSeekable(con)

truncate(con, ...)

Arguments

con | a connection.
where | numeric. A file position (relative to the origin specified by origin), or NA.
rw | character. Empty or "read" or "write", partial matches allowed.
origin | character. One of "start", "current", "end": see Details.
... | further arguments passed to or from other methods.

Details

seek with where = NA returns the current byte offset of a connection (from the beginning), and with a non-missing where argument the connection is re-positioned (if possible) to the specified position. isSeekable returns whether the connection in principle supports seek: currently only (possibly gz-compressed) file connections do. gzfile connections do not support origin = "end"; the file position they use is that of the uncompressed file.

where is stored as a real but should represent an integer: non-integer values are likely to be truncated. Note that the possible values can exceed the largest representable number in an R integer on 64-bit OSes, and on some 32-bit OSes.

Clipboard connections can seek too.

We have found so many errors in the Windows implementation of file positioning that users are advised to use it only at their own risk, and asked not to waste the R developers' time with bug reports on Windows' deficiencies.

File connections can be open for both writing/appending, in which case R keeps separate positions for reading and writing. Which seek refers to can be set by its rw argument: the default is the last mode (reading or writing) which was used. Most files are only opened for reading or writing and so default to that state. If a file is open for reading and writing but has not been used, the default is to give the reading position (0).

The initial file position for reading is always at the beginning. The initial position for writing is at the beginning of the file for modes "r+" and "r+b", otherwise at the end of the file. Some platforms only allow writing at the end of the file in the append modes. (The reported write position for a file opened in an append mode will typically be unreliable until the file has been written to.)

truncate truncates a file opened for writing at its current position. It works only for file connections, and is not implemented on all platforms: on others (including Windows) it will not work for large (> 2Gb) files.

Value

seek returns the current position (before any move), as a (numeric) byte offset from the origin, if relevant, or 0 if not. Note that the position can exceed the largest representable number in an R integer on 64-bit OSes, and on some 32-bit OSes.
truncate returns NULL: it stops with an error if it fails (or is not implemented).
isSeekable returns a logical value, whether the connection supports seek.

See Also

connections


Sequence Generation

Description

Generate regular sequences. seq is a standard generic with a default method. seq.int is an internal generic which can be much faster but has a few restrictions. seq_along and seq_len are very fast primitives for two common cases.

Usage

seq(...)

## Default S3 method:
seq(from = 1, to = 1, by = ((to - from)/(length.out - 1)),
    length.out = NULL, along.with = NULL, ...)

seq.int(from, to, by, length.out, along.with, ...)

seq_along(along.with)
seq_len(length.out)

Arguments

... | arguments passed to or from methods.
from, to | the starting and (maximal) end value of the sequence.
by | number: increment of the sequence.
length.out | desired length of the sequence. A non-negative number, which for seq and seq.int will be rounded up if fractional.
along.with | take the length from the length of this argument.

Details

The interpretation of the unnamed arguments of seq and seq.int is not standard, and it is recommended always to name the arguments when programming.

Both seq are seq.int are generic, and only the default method is described here. Typical usages are

seq(from, to)
seq(from, to, by= )
seq(from, to, length.out= )
seq(along.with= )
seq(from)
seq(length.out= )
The first form generates the sequence from, from+/-1, ..., to (identical to from:to).

The second form generates from, from+by, ..., up to the sequence value less than or equal to to. Specifying to - from and by of opposite signs is an error.

The third generates a sequence of length.out equally spaced values from from to to. (length.out is usually abbreviated to length or len, and seq_len is much faster.)

The fourth form generates the sequence 1, 2, ..., length(along.with). (along.with is usually abbreviated to along, and seq_along is much faster.)

The fifth form generates the sequence 1, 2, ..., length(from) (as if argument along.with had been specified), unless the argument is numeric of length 1 when it is interpreted as 1:from (even for seq(0) for compatibility with S).

The final form generates 1, 2, ..., length.out unless length.out = 0, when it generates integer(0).

Very small sequences (with from - to of the order of 10^{-14} times the larger of the ends) will return from.

For seq(only), up to two of from, to and by can be supplied as complex values provided length.out or along.with is specified.

Value

Currently, the default method returns a result of type "integer" if from is (numerically equal to an) integer and, e.g., only to is specified, or also if only length or only along.with is specified. Note: this may change in the future and programmers should not rely on it.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

The methods seq.Date and seq.POSIXt.

:, rep, sequence, row, col.

Examples

seq(0, 1, length=11)
seq(rnorm(20))
seq(1, 9, by = 2) # match
seq(1, 9, by = pi)# stay below
seq(1, 6, by = 3)
seq(1.575, 5.125, by=0.05)
seq(17) # same as 1:17


Generate Regular Sequences of Dates

Description

The method for seq for date-time classes.

Usage

## S3 method for class 'Date':
seq(from, to, by, length.out = NULL, along.with = NULL, ...)

Arguments

from | starting date. Required
to | end date. Optional.
by | increment of the sequence. Optional. See Details.
length.out | integer, optional. desired length of the sequence.
along.with | take the length from the length of this argument.
... | arguments passed to or from other methods.

Details

by can be specified in several ways.

  • A number, taken to be in days.
  • A object of class difftime
  • A character string, containing one of "day", "week", "month" or "year". This can optionally be preceded by a (positive or negative) integer and a space, or followed by "s".

    See seq.POSIXt for the details of "month".

Value

A vector of class "Date".

See Also

Date

Examples

## first days of years
seq(as.Date("1910/1/1"), as.Date("1999/1/1"), "years")
## by month
seq(as.Date("2000/1/1"), by="month", length=12)
## quarters
seq(as.Date("2000/1/1"), as.Date("2003/1/1"), by="3 months")

## find all 7th of the month between two dates, the last being a 7th.
st <- as.Date("1998-12-17")
en <- as.Date("2000-1-7")
ll <- seq.Date(en, st, by="-1 month")
rev(ll[ll > st & ll < en])


Generate Regular Sequences of Dates

Description

The method for seq for date-time classes.

Usage

## S3 method for class 'POSIXt':
seq(from, to, by, length.out = NULL, along.with = NULL, ...)

Arguments

from | starting date. Required.
to | end date. Optional.
by | increment of the sequence. Optional. See Details.
length.out | integer, optional. desired length of the sequence.
along.with | take the length from the length of this argument.
... | arguments passed to or from other methods.

Details

by can be specified in several ways.

  • A number, taken to be in seconds.
  • A object of class difftime
  • A character string, containing one of "sec", "min", "hour", "day", "DSTday", "week", "month" or "year". This can optionally be preceded by a (positive or negative) integer and a space, or followed by "s".

The difference between "day" and "DSTday" is that the former ignores changes to/from daylight savings time and the latter takes the same clock time each day. ("week" ignores DST (it is a period of 144 hours), but "7 DSTdays") can be used as an alternative. "month" and "year" allow for DST.)

The timezone of the result is taken from from: remember than GMT does not have daylight savings time.

Using "month" first advances the month without changing the day: if this results in an invalid day of the month, it is counted forward into the next month: see the examples.

Value

A vector of class "POSIXct".

See Also

DateTimeClasses

Examples

## first days of years
seq(ISOdate(1910,1,1), ISOdate(1999,1,1), "years")
## by month
seq(ISOdate(2000,1,1), by = "month", length = 12)
seq(ISOdate(2000,1,31), by = "month", length = 4)
## quarters
seq(ISOdate(1990,1,1), ISOdate(2000,1,1), by = "3 months")
## days vs DSTdays: use c() to lose the timezone.
seq(c(ISOdate(2000,3,20)), by = "day", length = 10)
seq(c(ISOdate(2000,3,20)), by = "DSTday", length = 10)
seq(c(ISOdate(2000,3,20)), by = "7 DSTdays", length = 4)


Create A Vector of Sequences

Description

For each element of nvec the sequence seq(nvec[i]) is created. These are appended and the result returned.

Usage

sequence(nvec)

Arguments

nvec an integer vector each element of which specifies the upper bound of a sequence.

See Also

gl, seq, rep.

Examples

sequence(c(3,2))# the concatenated sequences 1:3 and 1:2.
#> [1] 1 2 3 1 2


Simple Serialization Interface

Description

A simple low level interface for serializing to connections.

Usage

serialize(object, connection, ascii = FALSE, refhook = NULL)

unserialize(connection, refhook = NULL)

.saveRDS(object, file = "", ascii = FALSE, version = NULL,
         compress = TRUE, refhook = NULL)

.readRDS(file, refhook = NULL)

Arguments

object | R object to serialize.
file | a connection or the name of the file where the R object is saved to or read from, or NULL for serialize or for unserialize an object returned by serialize (see Details).
ascii | a logical. If TRUE, an ASCII representation is written; otherwise (default), a more compact binary one is used.
version | the workspace format version to use. NULL specifies the current default format. The version used from R 0.99.0 to R 1.3.1 was version 1. The default format as from R 1.4.0 is version 2.
compress | a logical specifying whether saving to a named file is to use compression. Ignored when file is a connection and for workspace format version 1.
connection | an open connection, a raw vector or a length-one character vector.
refhook | a hook function for handling reference objects.

Details

The function serialize writes object to the specified connection. Sharing of reference objects is preserved within the object but not across separate calls to serialize. If connection is NULL then object is serialized to a raw vector, which is returned as the result of serialize. For a text mode connection, the default value of ascii is set to TRUE.

unserialize reads an object (as written by serialize) from connection or a raw vector or (for compatibility with earlier versions of serialize) a length-one character vector.

The refhook functions can be used to customize handling of non-system reference objects (all external pointers and weak references, and all environments other than name space and package environments and .GlobalEnv). The hook function for serialize should return a raw vector for references it wants to handle; otherwise it should return NULL. The hook for unserialize will be called with raw vectors supplied to serialize and should return an appropriate object.

Value

For serialize, NULL unless connection = NULL, when the result is stored in a raw vector.
For unserialize and .readRDS, an R object.
For .saveRDS, NULL invisibly.

Warning

These functions are still experimental. Names, interfaces and values might change in future versions (and the value of serialize was changed for R 2.4.0). .saveRDS and .readRDS are intended for internal use.

Examples

x <- serialize(list(1,2,3), NULL)
unserialize(x)
## test earlier interface as a length-one character vector
y <- rawToChar(x)
unserialize(y)


Set Operations

Description

Performs set union, intersection, (asymmetric!) difference, equality and membership on two vectors.

Usage

union(x, y)
intersect(x, y)
setdiff(x, y)
setequal(x, y)
is.element(el, set)

Arguments

x, y, el, set vectors (of the same mode) containing a sequence of items (conceptually) with no duplicated values.

Details

Each of union, intersect and setdiff will remove any duplicated values in the arguments.

is.element(x, y) is identical to x %in% y.

Value

A vector of the same mode as x or y for setdiff and intersect, respectively, and of a common mode for union.
A logical scalar for setequal and a logical of the same length as x for is.element.

See Also

%in%

Examples

(x <- c(sort(sample(1:20, 9)),NA))
(y <- c(sort(sample(3:23, 7)),NA))
union(x, y)
intersect(x, y)
setdiff(x, y)
setdiff(y, x)
setequal(x, y)

## True for all possible x & y :
setequal( union(x,y),
          c(setdiff(x,y), intersect(x,y), setdiff(y,x)))

is.element(x, y)# length 10
is.element(y, x)# length  8


Invoke a System Command, using a Shell

shell(base) R Documentation

Invoke a System Command using a Shell

Description

shell runs the command specified by cmd, usually under a shell.

Usage

shell(cmd, shell, flag = "/c", intern = FALSE, wait = TRUE,
      translate = FALSE, mustWork = FALSE, ...)

Arguments

cmd | the system command to be invoked, as a string.
shell | a string giving the name of the shell to be used, or NULL (no shell). If missing, a suitable shell is chosen: see ‘Details’.
flag | the switch to run a command under the shell. If the shell is bash or tcsh the default is changed to "-c".
intern | a logical, indicates whether to make the output of the command an R object.
wait | should the R interpreter wait for the command to finish? The default is to wait, and the interpreter will always wait if intern = TRUE.
translate | If TRUE, "/" in cmd is translated to "\".
mustWork | a logical; if TRUE failure to run the command will give an R error.
... | additional arguments to system.

Details

If no shell is specified, the environment variables R_SHELL, SHELL and COMSPEC are tried in turn: COMSPEC should always succeed. Using shell=NULL invokes the command cmd directly, in which case an extension of .exe is assumed. It is possible to use batch files directly if their extension is given: Windows (rather than R) then chooses a shell.

See system for fuller details: shell is a more user-friendly wrapper for system. To make use of Windows file associations, use shell.exec.

Value

If intern=TRUE, a character vector giving the output of the command, one line per character string, or an error message if the command could not be run.
If intern=FALSE, the return value is an error code, given the invisible attribute (so needs to be printed explicitly). If the command could not be run for any reason, the value is -1 and an R warning is generated. Otherwise if wait=FALSE the value is the error code returned by the command, and if wait=TRUE it is the zero (the conventional success value),
If intern=FALSE and wait=TRUE (the defaults) the text output from a command that is a console application will appear in the R console (Rgui) or the window running R (Rterm).

See Also

system, shell.exec


Open a File or URL using Windows File Associations

Description

Opens the specified file or URL using the application specified in the Windows file associations.

Usage

shell.exec(file)

Arguments

file file or URL to be opened.

Details

It is likely that file needs to be a complete path, e.g. ‘"c:/R/results.html"’ or ‘"c:R\results.html"’ as most applications interpret files relative to their working directory.

Encoded file:// URLs are not usually accepted.

Value

No value, but informative error messages will be given if the operation fails.

Author(s)

B. D. Ripley

See Also

system, shell

Examples

## Not run:
## the space should not be encoded here
shell.exec("C:\Program Files\BreezeSys\BreezeBrowser\Breezebrowser.htm")
shell.exec("C:/Program Files/BreezeSys/BreezeBrowser/Breezebrowser.htm")
shell.exec("file://C:/Program Files/BreezeSys/BreezeBrowser/Breezebrowser.htm")
## End(Not run)


Display Connections

Description

Display aspects of connections.

Usage

showConnections(all = FALSE)
getConnection(what)
closeAllConnections()

stdin()
stdout()
stderr()

Arguments

all | logical: if true all connections, including closed ones and the standard ones are displayed. If false only open user-created connections are included.
what | integer: a row number of the table given by showConnections.

Details

stdin(), stdout() and stderr() are standard connections corresponding to input, output and error on the console respectively (and not necessarily to file streams). They are text-mode connections of class "terminal" which cannot be opened or closed, and are read-only, write-only and write-only respectively. The stdout() and stderr() connections can be re-directed by sink.

showConnections returns a matrix of information. If a connection object has been lost or forgotten, getConnection will take a row number from the table and return a connection object for that connection, which can be used to close the connection, for example.

closeAllConnections closes (and destroys) all open user connections, restoring all sink diversions as it does so.

Value

stdin(), stdout() and stderr() return connection objects.
showConnections returns a character matrix of information with a row for each connection, by default only for open non-standard connections.
getConnection returns a connection object, or NULL.

See Also

connections

Examples

showConnections(all = TRUE)

textConnection(letters)
# oops, I forgot to record that one
showConnections()
#  class     description      mode text   isopen   can read can write
#3 "letters" "textConnection" "r"  "text" "opened" "yes"    "no"
## Not run: close(getConnection(3))

showConnections()


Quote Strings for Use in OS Shells

Description

Quote a string to be passed to an operating system shell.

Usage

shQuote(string, type = c("sh", "csh", "cmd"))

Arguments

string | a character vector, usually of length one.
type | character: the type of shell. Partial matching is supported. "cmd" refers to the Windows NT shell, and is the default under Windows.

Details

The default type of quoting supported under Unix-alikes is that for the Bourne shell sh. If the string does not contain single quotes, we can just surround it with single quotes. Otherwise, the string is surrounded in double quotes, which suppresses all special meanings of metacharacters except dollar, backquote and backslash, so these (and of course double quote) are preceded by backslash. This type of quoting is also appropriate for ksh, zsh and bash.

The other type of quoting is for the C-shell (csh and tcsh). Once again, if the string does not contain single quotes, we can just surround it with single quotes. If it does contain single quotes, we can use double quotes provided it does not contain dollar or backquote (and we need to escape backslash, exclamation mark and double quote). As a last resort, we need to split the string into pieces not containing single quotes and surround each with single quotes, and the single quotes with double quotes.

The Windows shell supports only double quoting. All this implementation does is to surround by double quotes and escape internal double quotes by a backslash. As Windows path names cannot contain double quotes, this makes shQuote safe for use with system and with shell if the default shell is used.

It will usually be safe to use shQuote to quote arguments of a command, but because system does not use a shell, interpretation of quoted arguments is done by the run-time code of the executable.

References

Loukides, M. et al (2002) Unix Power Tools Third Edition. O'Reilly. Section 27.12.

http://www.mhuffman.com/notes/dos/bash_cmd.htm

See Also

Quotes for quoting R code.

sQuote for quoting English text.

Examples

test <- "abc$def`gh`i\\j"
cat(shQuote(test), "\n")
## Not run: system(paste("echo", shQuote(test)))
test <- "don't do it!"
cat(shQuote(test), "\n")

tryit <- "use the `-c' switch\nlike this"
cat(shQuote(tryit), "\n")
## Not run: system(paste("echo", shQuote(tryit)))
cat(shQuote(tryit, type="csh"), "\n")

## Windows-only example.
perlcmd <- 'print "Hello World\n";'
## Not run: shell(paste("perl -e", shQuote(perlcmd, type="cmd")))


Sign Function

Description

sign returns a vector with the signs of the corresponding elements of x (the sign of a real number is 1, 0, or -1 if the number is positive, zero, or negative, respectively).

Note that sign does not operate on complex vectors.

Usage

sign(x)

Arguments

x a numeric vector

Details

This is a generic function: methods can be defined for it directly or via the Math group generic.

See Also

abs

Examples

sign(pi) # == 1
sign(-2:3)# -1 -1 0 1 1 1


Send R Output to a File

Description

sink diverts R output to a connection.

sink.number() reports how many diversions are in use.

sink.number(type = "message") reports the number of the connection currently being used for error messages.

Usage

sink(file = NULL, append = FALSE, type = c("output", "message"),
     split = FALSE)

sink.number(type = c("output", "message"))

Arguments

file | a connection or a character string naming the file to write to, or NULL to stop sink-ing.
append | logical. If TRUE, output will be appended to file; otherwise, it will overwrite the contents of file.
type | character. Either the output stream or the messages stream.
split | logical: if TRUE, output will be sent to the new sink and to the current output stream, like the Unix program tee.

Details

sink diverts R output to a connection. If file is a character string, a file connection with that name will be established for the duration of the diversion.

Normal R output is diverted by the default type = "output". Only prompts and warning/error messages continue to appear on the terminal. The latter can diverted by type = "message" (see below).

sink() or sink(file=NULL) ends the last diversion (of the specified type). There is a stack of diversions for normal output, so output reverts to the previous diversion (if there was one). The stack is of up to 21 connections (20 diversions).

If file is a connection it will be opened if necessary.

Sink-ing the messages stream should be done only with great care. For that stream file must be an already open connection, and there is no stack of connections.

Value

sink returns NULL.
For sink.number() the number (0, 1, 2, ...) of diversions of output in place.
For sink.number("message") the connection number used for messages, 2 if no diversion has been used.

Warning

Don't use a connection that is open for sink for any other purpose. The software will stop you closing one such inadvertently.

Do not sink the messages stream unless you understand the source code implementing it and hence the pitfalls.

Note

sink(split = TRUE) is only available on systems which support the C99 function va_copy (or under the name __va_copy), but we know of no current systems which do not.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language. Springer.

See Also

capture.output

Examples

sink("sink-examp.txt")
i <- 1:10
outer(i, i, "*")
sink()
unlink("sink-examp.txt")
## Not run:
## capture all the output to a file.
zz <- file("all.Rout", open="wt")
sink(zz)
sink(zz, type="message")
try(log("a"))
## back to the console
sink(type="message")
sink()
try(log("a"))
## End(Not run)


Slice Indexes in an Array

Description

Returns a matrix of integers indicating the number of their slice in a given array.

Usage

slice.index(x, MARGIN)

Arguments

x | an array. If x has no dimension attribute, it is considered a one-dimensional array.
MARGIN | an integer giving the dimension number to slice by.

Value

An integer array y with dimensions corresponding to those of x such that all elements of slice number i with respect to dimension MARGIN have value i.

See Also

row and col for determining row and column indexes; in fact, these are special cases of slice.index corresponding to MARGIN equal to 1 and 2, respectively when x is a matrix.

Examples

x <- array(1 : 24, c(2, 3, 4))
slice.index(x, 2)


Extract Slots

Description

Extract tbe contents of a slot in a object with a formal class structure.

Usage

object@name

Arguments

object | An object from a formally defined class.
name | The character-string name of the slot.

Details

This operator supports the formal classes of package methods, and is disabled unless the methods is loaded. See slot for further details.

Currently there is no checking that the object is an instance of a formal class, nor that name is a slot name.

See Also

Extract, slot


Wait on Socket Connections

Description

Waits for the first of several socket connections to become available.

Usage

socketSelect(socklist, write = FALSE, timeout = NULL)

Arguments

socklist | list of open socket connections
write | logical. If TRUE wait for corresponding socket to become available for writing; otherwise wait for it to become available for reading.
timeout | numeric or NULL. Time in seconds to wait for a socket to become available; NULL means wait indefinitely.

Details

The values in write are recycled if necessary to make up a logical vector the same length as socklist. Socket connections can appear more than once in socklist; this can be useful if you want to determine whether a socket is available for reading or writing.

Value

Logical the same length as socklist indicating whether the corresponding socket connection is available for output or input, depending on the corresponding value of write.

Examples

## Not run:
## test whether socket connection s is available for writing or reading
socketSelect(list(s,s),c(TRUE,FALSE),timeout=0)
## End(Not run)


Solve a System of Equations

Description

This generic function solves the equation a %*% x = b for x, where b can be either a vector or a matrix.

Usage

solve(a, b, ...)

## Default S3 method:
solve(a, b, tol, LINPACK = FALSE, ...)

Arguments

a | a square numeric or complex matrix containing the coefficients of the linear system.
b | a numeric or complex vector or matrix giving the right-hand side(s) of the linear system. If missing, b is taken to be an identity matrix and solve will return the inverse of a.
tol | the tolerance for detecting linear dependencies in the columns of a. If LINPACK is TRUE the default is 1e-7, otherwise it is .Machine$double.eps. Future versions of R may use a tighter tolerance. Not presently used with complex matrices a.
LINPACK | logical. Should LINPACK be used (for compatibility with R < 1.7.0)? Otherwise LAPACK is used.
... | further arguments passed to or from other methods

Details

a or b can be complex, but this uses double complex arithmetic which might not be available on all platforms and LAPACK will always be used.

The row and column names of the result are taken from the column names of a and of b respectively. As from R 1.7.0 if b is missing the column names of the result are the row names of a. No check is made that the column names of a and the row names of b are equal.

For back-compatibility a can be a (real) QR decomposition, although qr.solve should be called in that case. qr.solve can handle non-square systems.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

solve.qr for the qr method, chol2inv for inverting from the Choleski factor backsolve, qr.solve.

Examples

hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
h8 <- hilbert(8); h8
sh8 <- solve(h8)
round(sh8 %*% h8, 3)

A <- hilbert(4)
A[] <- as.complex(A)
## might not be supported on all platforms
try(solve(A))


Sorting or Ordering Vectors

Description

Sort (or order) a vector or factor (partially) into ascending (or descending) order. For ordering along more than one variable, e.g., for sorting data frames, see order.

Usage

sort(x, decreasing = FALSE, ...)

## Default S3 method:
sort(x, decreasing = FALSE, na.last = NA, ...)

sort.int(x, partial = NULL, na.last = NA, decreasing = FALSE,
         method = c("shell", "quick"), index.return = FALSE)

is.unsorted(x, na.rm = FALSE)

Arguments

x | for sort, an R object with a class or a numeric, complex, character or logical vector. For sort.int, a numeric, complex, character or logical vector, or a factor.
decreasing | logical. Should the sort be increasing or decreasing? Not available for partial sorting.
... | arguments to be passed to or from methods or (for the default methods and objects without a class) to sim.int.
na.last | for controlling the treatment of NAs. If TRUE, missing values in the data are put last; if FALSE, they are put first; if NA, they are removed.
partial | NULL or an integer vector of indices for partial sorting.
method | character string specifying the algorithm used.
index.return | logical indicating if the ordering index vector should be returned as well; this is only available for a few cases, the default na.last = NA and full sorting of non-factors.
na.rm | logical. Should missing values be removed?

Details

sort is a generic function for which methods can be written, and sort.int is the internal method which is compatible with S if only the first three arguments are used.

If partial is not NULL, it is taken to contain indices of elements of x which are to be placed in their correct positions by partial sorting. After the sort, the values specified in partial are in their correct position in the sorted array. Any values smaller than these values are guaranteed to have a smaller index in the sorted array and any values which are greater are guaranteed to have a bigger index in the sorted array. (This is included for efficiency, and many of the options are not available for partial sorting. It is only substantially more efficient if partial has a handful of elements, and a full sort is done if there are more than 10.) Names are discarded for partial sorting.

Complex values are sorted first by the real part, then the imaginary part.

The sort order for character vectors will depend on the collating sequence of the locale in use: see Comparison. The sort order for factors is the order of their levels (which is particularly appropriate for ordered factors).

is.unsorted returns a logical indicating if x is sorted increasingly, i.e., is.unsorted(x) is true if any(x != sort(x)) (and there are no NAs).

Method "shell" uses Shellsort (an O(n^{4/3}) variant from Sedgewick (1996)). If x has names a stable sort is used, so ties are not reordered. (This only matters if names are present.)

Method "quick" uses Singleton's Quicksort implementation and is only available when x is numeric (double or integer) and partial is NULL. (For other types of x Shellsort is used, silently.) It is normally somewhat faster than Shellsort (perhaps twice as fast on vectors of length a million) but has poor performance in the rare worst case. (Peto's modification using a pseudo-random midpoint is used to make the worst case rarer.) This is not a stable sort, and ties may be reordered.

Value

For sort, the result depends on the S3 method which is dispatched. If x does not have a class the rest of this section applies. For classed objects which do not have a specific method the default method will be used and is equivalent to x[order(x, ...)]: this depends on the class having a suitable method for [ (and also that order will work, which is not the case for a class based on a list).
For sort.int the sorted vector unless index.return is true, when the result is a list with components named x and ix containing the sorted numbers and the ordering index vector. In the latter case, if method == "quick" ties may be reversed in the ordering, unlike sort.list, as quicksort is not stable.
All attributes are removed from the return value (see Becker et al, 1988, p.146) except names, which are sorted. (If partial is specified even the names are removed.) Note that this means that the returned value has no class, except for factors and ordered factors (which are treated specially and whose result is transformed back to the original class).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Sedgewick, R. (1986) A new upper bound for Shell sort. J. Algorithms 7, 159–173.

Singleton, R. C. (1969) An efficient algorithm for sorting with minimal storage: Algorithm 347. Communications of the ACM 12, 185–187.

See Also

order for sorting on or reordering multiple variables.

rank.

Examples

require(stats)
x <- swiss$Education[1:25]
x; sort(x); sort(x, partial = c(10, 15))
stats:::median.default # shows you another example for 'partial'

## illustrate 'stable' sorting (of ties):
sort(c(10:3,2:12), method = "sh", index=TRUE) # is stable
## $x : 2  3  3  4  4  5  5  6  6  7  7  8  8  9  9 10 10 11 12
## $ix: 9  8 10  7 11  6 12  5 13  4 14  3 15  2 16  1 17 18 19
sort(c(10:3,2:12), method = "qu", index=TRUE) # is not
## $x : 2  3  3  4  4  5  5  6  6  7  7  8  8  9  9 10 10 11 12
## $ix: 9 10  8  7 11  6 12  5 13  4 14  3 15 16  2 17  1 18 19
##        ^^^^^

## Not run: ## Small speed comparison simulation:
N <- 2000
Sim <- 20
rep <- 1000 # << adjust to your CPU
c1 <- c2 <- numeric(Sim)
for(is in 1:Sim){
  x <- rnorm(N)
  c1[is] <- system.time(for(i in 1:rep) sort(x, method = "shell"))[1]
  c2[is] <- system.time(for(i in 1:rep) sort(x, method = "quick"))[1]
  stopifnot(sort(x, method = "s") == sort(x, method = "q"))
}
rbind(ShellSort = c1, QuickSort = c2)
cat("Speedup factor of quick sort():\n")
summary({qq <- c1 / c2; qq[is.finite(qq)]})

## A larger test
x <- rnorm(1e7)
system.time(x1 <- sort(x, method = "shell"))
system.time(x2 <- sort(x, method = "quick"))
stopifnot(identical(x1, x2))
## End(Not run)


Read R Code from a File or a Connection

Description

source causes R to accept its input from the named file or URL (the name must be quoted) or connection. Input is read and parsed by from that file until the end of the file is reached, then the parsed expressions are evaluated sequentially in the chosen environment.

Usage

source(file, local = FALSE, echo = verbose, print.eval = echo,
       verbose = getOption("verbose"),
       prompt.echo = getOption("prompt"),
       max.deparse.length = 150, chdir = FALSE,
       encoding = getOption("encoding"))

Arguments

file | a connection or a character string giving the pathname of the file or URL to read from.
local | if local is FALSE, the statements scanned are evaluated in the user's workspace (the global environment), otherwise in the environment calling source.
echo | logical; if TRUE, each expression is printed after parsing, before evaluation.
print.eval | logical; if TRUE, the result of eval(i) is printed for each expression i; defaults to echo.
verbose | if TRUE, more diagnostics (than just echo = TRUE) are printed during parsing and evaluation of input, including extra info for each expression.
prompt.echo | character; gives the prompt to be used if echo = TRUE.
max.deparse.length | integer; is used only if echo is TRUE and gives the maximal length of the “echo” of a single expression.
chdir | logical; if TRUE and file is a pathname, the R working directory is temporarily changed to the directory containing file for evaluating.
encoding | character string. The encoding to be assumed when file is a character string: see file. A possible value is "unknown": see the Details.

Details

All versions of R accept input from a connection with end of line marked by LF (as used on Unix), CRLF (as used on DOS/Windows) or CR (as used on classic MacOS). The final line can be incomplete, that is missing the final EOL marker.

If options("keep.source") is true (the default), the source of functions is kept so they can be listed exactly as input. This imposes a limit of 128K bytes on the function size and a nesting limit of 265. Use option(keep.source = FALSE) when these limits might take effect: if exceeded they generate an error.

This paragraph applies if file is a filename (rather than a connection). If encoding = "unknown", an attempt is made to guess the encoding. The result of localeToCharset() is used a guide. If encoding has two or more elements, they are tried in turn until the file/URL can be read without error in the trial encoding.

Unlike input from a console, lines in the file or on a connection can contain an unlimited number of characters. However, there is a limit of 8192 bytes on the size of character strings.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

demo which uses source;
eval, parse and scan;
options("keep.source").

Examples

## If you want to source() a bunch of files, something like
## the following may be useful:
 sourceDir <- function(path, trace = TRUE, ...) {
    for (nm in list.files(path, pattern = "\\.[RrSsQq]$")) {
       if(trace) cat(nm,":")
       source(file.path(path, nm), ...)
       if(trace) cat("\n")
    }
 }


Special Functions of Mathematics

Description

Special mathematical functions related to the beta and gamma functions.

Usage

beta(a, b)
lbeta(a, b)
gamma(x)
lgamma(x)
psigamma(x, deriv = 0)
digamma(x)
trigamma(x)
choose(n, k)
lchoose(n, k)
factorial(x)
lfactorial(x)

Arguments

a, b, x, n | numeric vectors.
k, deriv | integer vectors.

Details

The functions beta and lbeta return the beta function and the natural logarithm of the beta function,

B(a,b) = (Gamma(a)Gamma(b))/(Gamma(a+b)).

The formal definition is

integral_0^1 t^(a-1) (1-t)^(b-1) dt

(Abramowitz and Stegun (6.2.1), page 258).

The functions gamma and lgamma return the gamma function Γ(x) and the natural logarithm of the absolute value of the gamma function. The gamma function is defined by (Abramowitz and Stegun (6.1.1), page 255)

integral_0^Inf t^(a-1) exp(-t) dt

factorial(x) is x! and identical to gamma(x+1) and lfactorial is lgamma(x+1).

The functions digamma and trigamma return the first and second derivatives of the logarithm of the gamma function. psigamma(x, deriv) (deriv >= 0) is more generally computing the deriv-th derivative of psi(x).

digamma(x) = psi(x) = d/dx {ln Gamma(x)} = Gamma'(x) / Gamma(x)

The functions choose and lchoose return binomial coefficients and their logarithms. Note that choose(n,k) is defined for all real numbers n and integer k. For k >= 1 as n(n-1)...(n-k+1) / k!, as 1 for k = 0 and as 0 for negative k.
choose(*,k) uses direct arithmetic (instead of [l]gamma calls) for small k, for speed and accuracy reasons. Note the function combn (package utils) for enumeration of all possible combinations.

The gamma, lgamma, digamma and trigamma functions are generic: methods can be defined for them individually or via the Math group generic.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole. (for gamma and lgamma.)

Abramowitz, M. and Stegun, I. A. (1972) Handbook of Mathematical Functions. New York: Dover. Chapter 6: Gamma and Related Functions.

See Also

Arithmetic for simple, sqrt for miscellaneous mathematical functions and Bessel for the real Bessel functions.

For the incomplete gamma function see pgamma.

Examples

choose(5, 2)
for (n in 0:10) print(choose(n, k = 0:n))

factorial(100)
lfactorial(10000)

## gamma has 1st order poles at 0, -1, -2, ...
## this will generate loss of precision warnings, so turn off
op <- options("warn")
options(warn = -1)
x <- sort(c(seq(-3,4, length=201), outer(0:-3, (-1:1)*1e-6, "+")))
plot(x, gamma(x), ylim=c(-20,20), col="red", type="l", lwd=2,
     main=expression(Gamma(x)))
abline(h=0, v=-3:0, lty=3, col="midnightblue")
options(op)

x <- seq(.1, 4, length = 201); dx <- diff(x)[1]
par(mfrow = c(2, 3))
for (ch in c("", "l","di","tri","tetra","penta")) {
  is.deriv <- nchar(ch) >= 2
  nm <- paste(ch, "gamma", sep = "")
  if (is.deriv) {
    dy <- diff(y) / dx # finite difference
    der <- which(ch == c("di","tri","tetra","penta")) - 1
    nm2 <- paste("psigamma(*, deriv = ", der,")",sep='')
    nm  <- if(der >= 2) nm2 else paste(nm, nm2, sep = " ==\n")
    y <- psigamma(x, deriv=der)
  } else {
    y <- get(nm)(x)
  }
  plot(x, y, type = "l", main = nm, col = "red")
  abline(h = 0, col = "lightgray")
  if (is.deriv) lines(x[-1], dy, col = "blue", lty = 2)
}
par(mfrow = c(1, 1))

## "Extended" Pascal triangle:
fN <- function(n) formatC(n, wid=2)
for (n in -4:10) cat(fN(n),":", fN(choose(n, k= -2:max(3,n+2))), "\n")

## R code version of choose()  [simplistic; warning for k < 0]:
mychoose <- function(r,k)
    ifelse(k <= 0, (k==0),
           sapply(k, function(k) prod(r:(r-k+1))) / factorial(k))
k <- -1:6
cbind(k=k, choose(1/2, k), mychoose(1/2, k))

## Binomial theorem for n=1/2 ;
## sqrt(1+x) = (1+x)^(1/2) = sum_{k=0}^Inf  choose(1/2, k) * x^k :
k <- 0:10 # 10 is sufficient for ~ 9 digit precision:
sqrt(1.25)
sum(choose(1/2, k)* .25^k)


Divide into Groups

Description

split divides the data in the vector x into the groups defined by f. The replacement forms replace values corresponding to such a division. unsplit reverses the effect of split.

Usage

split(x, f, drop = FALSE, ...)
split(x, f, drop = FALSE, ...) <- value
unsplit(value, f, drop = FALSE)

Arguments

x | vector or data frame containing values to be divided into groups.
f | a “factor” in the sense that as.factor(f) defines the grouping, or a list of such factors in which case their interaction is used for the grouping.
drop | logical indicating if levels that do not occur should be dropped (if f is a factor or a list).
value | a list of vectors or data frames compatible with a splitting of x. Recycling applies if the lengths do not match.
... | further potential arguments passed to methods.

Details

split and split<- are generic functions with default and data.frame methods.

f is recycled as necessary and if the length of x is not a multiple of the length of f a warning is printed. unsplit works only with lists of vectors. The data frame method can also be used to split a matrix into a list of matrices, and the replacement form likewise, provided they are invoked explicitly.

Any missing values in f are dropped together with the corresponding values of x.

Value

The value returned from split is a list of vectors containing the values for the groups. The components of the list are named by the used factor levels given by f. (If f is longer than x then some of the components will be of zero length.)
The replacement forms return their right hand side. unsplit returns a vector for which split(x, f) equals value

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

cut

Examples

require(stats)
n <- 10; nn <- 100
g <- factor(round(n * runif(n * nn)))
x <- rnorm(n * nn) + sqrt(as.numeric(g))
xg <- split(x, g)
boxplot(xg, col = "lavender", notch = TRUE, varwidth = TRUE)
sapply(xg, length)
sapply(xg, mean)

## Calculate z-scores by group

z <- unsplit(lapply(split(x, g), scale), g)
tapply(z, g, mean)

# or

z <- x
split(z, g) <- lapply(split(x, g), scale)
tapply(z, g, sd)

## Split a matrix into a list by columns
ma <- cbind(x = 1:10, y = (-4:5)^2)
split(ma, col(ma))

split(1:10, 1:2)


Use C-style String Formatting Commands

Description

A wrapper for the C function sprintf, that returns a character vector containing a formatted combination of text and variable values.

Usage

sprintf(fmt, ...)
gettextf(fmt, ..., domain = NULL)

Arguments

fmt | a format string.
... | values to be passed into fmt. Only logical, integer, real and character vectors are supported, but some coercion will be done: see the Details section.
domain | see gettext.

Details

sprintf is a wrapper for the system sprintf C-library function. Attempts are made to check that the mode of the values passed match the format supplied, and R's special values (NA, Inf, -Inf and NaN) are handled correctly.

gettextf is a convenience function which provides C-style string formatting with possible translation of the format string.

The arguments (including fmt) are recycled if possible a whole number of times to the length of the longest, and then the formatting is done in parallel.

The following is abstracted from Kernighan and Ritchie (see References). The string fmt contains normal characters, which are passed through to the output string, and also special characters that operate on the arguments provided through .... Special characters start with a % and end with one of the letters in the set difeEgGsxX%. These letters denote the following types:

d, i, x, X
Integer value, x and X being hexadecimal (using the same case for a-f as the code). Numeric variables with exactly integer values will be coerced to integer.
f
Double precision value, in decimal notation of the form "[-]mmm.ddd". The number of decimal places is specified by the precision: the default is 6; a precision of 0 suppresses the decimal point.
e, E
Double precision value, in decimal notation of the form [-]m.ddde[+-]xx or [-]m.dddE[+-]xx.
g, G
Double precision value, in %e or %E format if the exponent is less than -4 or greater than or equal to the precision, and %f format otherwise.
s
Character string.
%
Literal % (none of the formatting characters given below are permitted in this case).

as.character is used for non-character arguments with s and as.double for non-double arguments with f, e, E, g, G. NB: the length is determined before conversion, so do not rely on the internal coercion if this would change the length.

In addition, between the initial % and the terminating conversion character there may be, in any order:

m.n
Two numbers separated by a period, denoting the field width (m) and the precision (n)
-
Left adjustment of converted argument in its field
+
Always print number with sign
a space
Prefix a space if the first number is not a sign
0
For numbers, pad to the field width with leading zeros

Further, immediately after % may come 1$ to 99$ to refer to the numbered argument: this allows arguments to be referenced out of order and is mainly intended for translators of error messages. If this is done it is best if all formats are numbered: if not the unnumbered ones process the arguments in order. See the examples.

A field width or precision (but not both) may be indicated by an asterisk *. In this case an argument specifies the desired number. A negative field width is taken as a '-' flag followed by a positive field width. A negative precision is taken as if the precision were omitted. The *1$ to *99$ notation for arguments referenced out of order is also supported.

The result has a length limit, probably 8192 bytes, and attempts to exceed this may result in an error, or truncation with a warning.

Value

A character vector of length that of the longest input. Character NAs are converted to "NA".

Author(s)

Original code by Jonathan Rougier, J.C.Rougier@durham.ac.uk.

References

Kernighan, B. W. and Ritchie, D. M. (1988) The C Programming Language. Second edition, Prentice Hall. describes the format options in table B-1 in the Appendix.

See Also

formatC for a way of formatting vectors of numbers in a similar fashion.

paste for another way of creating a vector combining text and values.

gettext for the mechanisms for the automated translation of text.

Examples

## be careful with the format: most things in R are floats
## only integer-valued reals get coerced to integer.

sprintf("%s is %f feet tall\n", "Sven", 7.1)      # OK
try(sprintf("%s is %i feet tall\n", "Sven", 7.1)) # not OK
try(sprintf("%s is %i feet tall\n", "Sven", 7))   # OK

## use a literal % :

sprintf("%.0f%% said yes (out of a sample of size %.0f)", 66.666, 3)

## various formats of pi :

sprintf("%f", pi)
sprintf("%.3f", pi)
sprintf("%1.0f", pi)
sprintf("%5.1f", pi)
sprintf("%05.1f", pi)
sprintf("%+f", pi)
sprintf("% f", pi)
sprintf("%-10f", pi) # left justified
sprintf("%e", pi)
sprintf("%E", pi)
sprintf("%g", pi)
sprintf("%g",   1e6 * pi) # -> exponential
sprintf("%.9g", 1e6 * pi) # -> "fixed"
sprintf("%G", 1e-6 * pi)

## no truncation:
sprintf("%1.f",101)

## re-use one argument three times, show difference between %x and %X
xx <- sprintf("%1$d %1$x %1$X", 0:15)
xx <- matrix(xx, dimnames=list(rep("", 16), "%d%x%X"))
noquote(format(xx, justify="right"))

## More sophisticated:

sprintf("min 10-char string '%10s'",
        c("a", "ABC", "and an even longer one"))

n <- 1:18
sprintf(paste("e with %2d digits = %.",n,"g",sep=""), n, exp(1))

## Using arguments out of order
sprintf("second %2$1.0f, first %1$5.2f, third %3$1.0f", pi, 2, 3)

## Using asterisk for width or precision
sprintf("precision %.*f, width '%*.3f'", 3, pi, 8, pi)

## Asterisk and argument re-use, 'e' example reiterated:
sprintf("e with %1$2d digits = %2$.*1$g", n, exp(1))

## re-cycle arguments
sprintf("%s %d", "test", 1:3)


Quote Text

Description

Single or double quote text by combining with appropriate single or double left and right quotation marks.

Usage

sQuote(x)
dQuote(x)

Arguments

x an R object, to be coerced to a character vector.

Details

The purpose of the functions is to provide a simple means of markup for quoting text to be used in the R output, e.g., in warnings or error messages. Note that English quoting conventions are used, whatever the locale in use.

The choice of the appropriate quotation marks depends on both the locale and the available character sets. Older Unix/X11 fonts displayed the grave accent (0x60) and the apostrophe (0x27) in a way that they could also be used as matching open and close single quotation marks. Using modern fonts, or non-Unix systems, these characters no longer produce matching glyphs. Unicode provides left and right single quotation mark characters (U+2018 and U+2019); if Unicode cannot be assumed, it seems reasonable to use the apostrophe as an undirectional single quotation mark.

Similarly, Unicode has left and right double quotation mark characters (U+201C and U+201D); if only ASCII's typewriter characteristics can be employed, than the ASCII quotation mark (0x22) should be used as both the left and right double quotation mark.

By default, sQuote and dQuote employ undirectional ASCII quotation style. In a UTF-8 locale (see l10n_info), the Unicode directional quotes are used.

References

Markus Kuhn, “ASCII and Unicode quotation marks”. http://www.cl.cam.ac.uk/~mgk25/ucs/quotes.html

See Also

Quotes for quoting R code.

shQuote for quoting OS commands.

Examples

paste("argument", sQuote("x"), "must be non-zero")


Stack or Unstack Vectors from a Data Frame or List

Description

Stacking vectors concatenates multiple vectors into a single vector along with a factor indicating where each observation originated. Unstacking reverses this operation.

Usage

stack(x, ...)
## Default S3 method:
stack(x, ...)
## S3 method for class 'data.frame':
stack(x, select, ...)

unstack(x, ...)
## Default S3 method:
unstack(x, form, ...)
## S3 method for class 'data.frame':
unstack(x, form = formula(x), ...)

Arguments

x | object to be stacked or unstacked
select | expression, indicating variables to select from a data frame
form | a two-sided formula whose left side evaluates to the vector to be unstacked and whose right side evaluates to the indicator of the groups to create. Defaults to formula(x) in unstack.data.frame.
... | further arguments passed to or from other methods.

Details

The stack function is used to transform data available as separate columns in a data frame or list into a single column that can be used in an analysis of variance model or other linear model. The unstack function reverses this operation.

Value

unstack produces a list of columns according to the formula form. If all the columns have the same length, the resulting list is coerced to a data frame.
stack produces a data frame with two columns

values | the result of concatenating the selected vectors in x
ind | a factor indicating from which vector in x the observation originated

Author(s)

Douglas Bates

See Also

lm, reshape

Examples

require(stats)
formula(PlantGrowth)         # check the default formula
pg <- unstack(PlantGrowth)   # unstack according to this formula
pg
stack(pg)                    # now put it back together
stack(pg, select = -ctrl)    # omitting one vector


Formal Method System – Creating Generic Functions

Description

This help page is for Routines which are primitives used with the methods package. They should not be used without it.

Usage

standardGeneric(f)

Details

standardGeneric dispatches the method defined for a generic function f, using the actual arguments in the frame from which it is called.

For more, use the methods package, and see the documentation in GenericFunctions.

Author(s)

John Chambers


Initialization at Start of an R Session

Description

In R, the startup mechanism is as follows.

Unless --no-environ was given on the command line, 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 R_ENVIRON; if this is unset or empty, ‘$R_HOME/etc/Renviron.site’ is used (if it exists, which it does not in a “factory-fresh” installation). The user files searched for are ‘.Renviron’ in the current or in the user's home directory (in that order). (See ‘See also’ for how the home directory is found on Windows. See Details for how the files are read.

Then R searches for the site-wide startup profile unless the command line option --no-site-file was given. The name of this file is taken from the value of the R_PROFILE environment variable. If this variable is unset, the default is ‘$R_HOME/etc/Rprofile.site’, which is used if it exists (which it does not in a “factory-fresh” installation). This code is loaded into package base. Users need to be careful not to unintentionally overwrite objects in base, and it is normally advisable to use local if code needs to be executed: see the examples.

Then, unless --no-init-file was given, R searches for a file called ‘.Rprofile’ in the current directory or in the user's home directory (in that order) and sources it into the user workspace.

It then loads a saved image of the user workspace from ‘.RData’ if there is one (unless --no-restore-data was specified, or --no-restore, on the command line).

Next, if a function .First is found on the search path, it is executed as .First(). Finally, function .First.sys() in the base package is run. This calls require to attach the default packages specified by options("defaultPackages"). If the methods package is included, this will have been attached earlier, by function .OptRequireMethods(), so that namespace initializations such as those from the user workspace will proceed correctly.

A function .First (and .Last) can be defined in appropriate ‘.Rprofile’ or ‘Rprofile.site’ files or have been saved in ‘.RData’. If you want a different set of packages than the default ones when you start, insert a call to options in the ‘.Rprofile’ or ‘Rprofile.site’ file. For example, options(defaultPackages = character()) will attach no extra packages on startup. Alternatively, set R_DEFAULT_PACKAGES=NULL as an environment variable before running R. Using options(defaultPackages = "") or R_DEFAULT_PACKAGES="" enforces the R system default.

The commands history is read from the file specified by the environment variable R_HISTFILE (default ‘.Rhistory’) unless --no-restore-history was specified (or --no-restore).

The command-line flag --vanilla implies --no-site-file, --no-init-file, --no-restore and --no-environ. In Windows, it also implies --no-Rconsole, which prevents loading the Rconsole file.

Usage

.First <- function() { ...... }

.Rprofile <startup file>

Details

Note that there are two sorts of files used in startup: environment files which contain lists of environment variables to be set, and profile files which contain R code.

Lines in a site or user environment file should be either comment lines starting with #, or lines of the form name=value. The latter sets the environmental variable name to value, overriding an existing value. If value contains an expression of the form ${foo-bar}, the value is that of the environmental variable foo if that exists and is set to a non-empty value, otherwise bar. (If it is of the form ${foo}, the default is "".) This construction can be nested, so bar can be of the same form (as in ${foo-${bar-blah}}). Note that the braces are essential: $HOME will not be interpreted.

Leading and trailing white space in value are stripped. value is processed in a similar way to a Unix shell. In particular the outermost level of (single or double) quotes is stripped, and backslashes are removed except inside quotes.

Note

Unix versions of R have a file ‘$R_HOME/etc/Renviron’ which is read very early in the start-up processing. It contains environment variables set by R in the configure process, and is not used on R for Windows.

See Also

For the definition of the home directory see the rw-FAQ. It can be found from a running R by Sys.getenv("R_USER").

.Last for final actions before termination. commandArgs for accessing the command line arguments.

An Introduction to R for more command-line options: those affecting memory management are covered in the help file for Memory.

For profiling code, see Rprof.

Examples

## Not run:
# Example ~/.Renviron on Unix
R_LIBS=~/R/library
PAGER=/usr/local/bin/less

# Example .Renviron on Windows
R_LIBS=C:/R/library
MY_TCLTK=yes
TCL_LIBRARY=c:/packages/Tcl/lib/tcl8.4

# Example of .Rprofile
options(width=65, digits=5)
options(show.signif.stars=FALSE)
ps.options(horizontal=FALSE)
set.seed(1234)
.First <- function() cat("\n   Welcome to R!\n\n")
.Last <- function()  cat("\n   Goodbye!\n\n")

# Example of Rprofile.site
local({
  old <- getOption("defaultPackages")
  options(defaultPackages = c(old, "MASS"))
})

## if .Renviron contains
FOOBAR="coo\bar"doh\ex"abc\"def'"

## then we get
> cat(Sys.getenv("FOOBAR"), "\n")
coo\bardoh\exabc"def'
## End(Not run)


Stop Function Execution

Description

stop stops execution of the current expression and executes an error action.

geterrmessage gives the last error message.

Usage

stop(..., call. = TRUE, domain = NULL)
geterrmessage()

Arguments

... | character vectors (which are pasted together with no separator), a condition object, or NULL.
call. | logical, indicating if the call should become part of the error message.
domain | see gettext. If NA, messages will not be translated.

Details

The error action is controlled by error handlers established within the executing code and by the current default error handler set by options(error=). The error is first signaled as if using signalCondition(). If there are no handlers or if all handlers return, then the error message is printed (if options("show.error.messages") is true) and the default error handler is used. The default behaviour (the NULL error-handler) in interactive use is to return to the top level prompt or the top level browser, and in non-interactive use to (effectively) call q("no", status=1, runLast=FALSE). The default handler stores the error message in a buffer; it can be retrieved by geterrmessage(). It also stores a trace of the call stack that can be retrieved by traceback().

Errors will be truncated to getOption("warning.length") characters, default 1000.

An attempt is made to coerce other types of inputs to character vectors.

Value

geterrmessage gives the last error message, as a character string ending in "\n".

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

warning, try to catch errors and retry, and options for setting error handlers. stopifnot for validity testing. tryCatch and withCallingHandlers can be used to establish custom handlers while executing an expression.

gettext for the mechanisms for the automated translation of messages.

Examples

options(error = expression(NULL))
# don't stop on stop(.)  << Use with CARE! >>

iter <- 12
if(iter > 10) stop("too many iterations")

tst1 <- function(...) stop("dummy error")
tst1(1:10, long, calling, expression)

tst2 <- function(...) stop("dummy error", call. = FALSE)
tst2(1:10, longcalling, expression, but.not.seen.in.Error)

options(error = NULL)# revert to default


Ensure the 'Truth' of R Expressions

Description

If any of the expressions in ... are not all TRUE, stop is called, producing an error message indicating the first of the elements of ... which were not true.

Usage

stopifnot(...)

Arguments

... any number of (logical) R expressions.

which should evaluate to TRUE.

Details

This function is intended for use in regression tests or also argument checking of functions, in particular to make them easier to read.

stopifnot(A, B) is conceptually equivalent to
{ if(any(is.na(A)) || !all(A)) stop(...) ;
           if(any(is.na(B)) || !all(B)) stop(...) }.

Value

(NULL if all statements in ... are TRUE.)

See Also

stop, warning.

Examples

stopifnot(1 == 1, all.equal(pi, 3.14159265), 1 < 2) # all TRUE

m <- matrix(c(1,3,3,1), 2,2)
stopifnot(m == t(m), diag(m) == rep(1,2)) # all(.) |=>  TRUE

op <- options(error = expression(NULL))
# "disable stop(.)"  << Use with CARE! >>

stopifnot(all.equal(pi, 3.141593),  2 < 2, all(1:10 < 12), "a" < "b")
stopifnot(all.equal(pi, 3.1415927), 2 < 2, all(1:10 < 12), "a" < "b")

options(op)# revert to previous error handler


Date-time Conversion Functions to and from Character

Description

Functions to convert between character representations and objects of classes "POSIXlt" and "POSIXct" representing calendar dates and times.

Usage

## S3 method for class 'POSIXct':
format(x, format = "", tz = "", usetz = FALSE, ...)
## S3 method for class 'POSIXlt':
format(x, format = "", usetz = FALSE, ...)

## S3 method for class 'POSIXt':
as.character(x, ...)

strftime(x, format="", usetz = FALSE, ...)
strptime(x, format, tz = "")

ISOdatetime(year, month, day, hour, min, sec, tz = "")
ISOdate(year, month, day, hour = 12, min = 0, sec = 0, tz = "GMT")

Arguments

x | An object to be converted.
tz | A timezone specification to be used for the conversion. System-specific, but "" is the current time zone, and "GMT" is UTC.
format | A character string. The default is "%Y-%m-%d %H:%M:%S" if any component has a time component which is not midnight, and "%Y-%m-%d" otherwise. If options("digits.secs") is set, up to the specified number of digits will be printed for seconds.
... | Further arguments to be passed from or to other methods.
usetz | logical. Should the timezone be appended to the output? This is used in printing times, and as a workaround for problems with using "%Z" on most Linux systems.
year, month, day | numerical values to specify a day.
hour, min, sec | numerical values for a time within a day. Fractional seconds are allowed.

Details

strftime is an alias for format.POSIXlt, and format.POSIXct first converts to class "POSIXlt" by calling as.POSIXlt. Note that only that conversion depends on the time zone.

The usual vector re-cycling rules are applied to x and format so the answer will be of length that of the longer of the vectors.

Locale-specific conversions to and from character strings are used where appropriate and available. This affects the names of the days and months, the AM/PM indicator (if used) and the separators in formats such as %x and %X.

The details of the formats are system-specific, but the following are defined by the ISO C / POSIX standard for strftime and are likely to be widely available. A conversion specification is introduced by %, usually followed by a single letter or O or E and then a single letter. Any character in the format string not part of a conversion specification is interpreted literally (and %% gives %). Widely implemented conversion specifications include

%a
Abbreviated weekday name in the current locale. (Also matches full name on input.)
%A
Full weekday name in the current locale. (Also matches abbreviated name on input.)
%b
Abbreviated month name in the current locale. (Also matches full name on input.)
%B
Full month name in the current locale. (Also matches abbreviated name on input.)
%c
Date and time, locale-specific.
%d
Day of the month as decimal number (01–31).
%H
Hours as decimal number (00–23).
%I
Hours as decimal number (01–12).
%j
Day of year as decimal number (001–366).
%m
Month as decimal number (01–12).
%M
Minute as decimal number (00–59).
%p
AM/PM indicator in the locale. Used in conjuction with %I and not with %H.
%S
Second as decimal number (00–61), allowing for up to two leap-seconds (but POSIX-compliant OSes will ignore leap seconds).
%U
Week of the year as decimal number (00–53) using the first Sunday as day 1 of week 1.
%w
Weekday as decimal number (0–6, Sunday is 0).
%W
Week of the year as decimal number (00–53) using the first Monday as day 1 of week 1.
%x
Date, locale-specific.
%X
Time, locale-specific.
%y
Year without century (00–99). If you use this on input, which century you get is system-specific. So don't! Often values up to 69 (or 68) are prefixed by 20 and 70(or 69) to 99 by 19.
%Y
Year with century.
%z, %Z
(output only.) Time zone as a character string (empty if not available). For %z this differs from POSIX.

Where leading zeros are shown they will be used on output but are optional on input. Windows allows the modifier # in conversion specifications for output: %#c and %#x use longer forms, and for dHIjmMSUwWyY leading zeros are suppressed.

Also defined in the current standards but less widely implemented (e.g. not for output on Windows) are

%C
Century (00–99): the integer part of the year divided by 100.
%D
Locale-specific date format such as %m/%d/%y: ISO C99 says it should be that exact format.
%e
Day of the month as decimal number ( 1–31), with a leading space for a single-digit number.
%F
Equivalent to %Y-%m-%d (the ISO 8601 date format).
%g
The last two digits of the week-based year (see %V). (Typically accepted but ignored on input.)
%G
The week-based year (see %V) as a decimal number. (Typically accepted but ignored on input.)
%h
Equivalent to %b.
%k
The 24-hour clock time with single digits preceded by a blank.
%l
The 12-hour clock time with single digits preceded by a blank.
%n
Newline on output, arbitrary whitespace on input.
%r
The 12-hour clock time (using the locale's AM or PM).
%R
Equivalent to %H:%M.
%t
Tab on output, arbitrary whitespace on input.
%T
Equivalent to %H:%M:%S.
%u
Weekday as a decimal number (1–7, Monday is 1).
%V
Week of the year as decimal number (00–53). If the week (starting on Monday) containing 1 January has four or more days in the new year, then it is considered week 1. Otherwise, it is the last week of the previous year, and the next week is week 1. (Typically accepted but ignored on input.)

For output (and possibly input) there are also %O[dHImMUVwWy] which may emit numbers in an alternative locale-dependent format (e.g. roman numerals), and %E[cCyYxX] which can use an alternative ‘era’ (e.g. a different religious calendar). Which of these are supported is OS-dependent.

Specific to R is %OSn, which for output gives the seconds to 0 <= n <= 6 decimal places (and if %OS is not followed by a digit, it uses the setting of getOption("digits.secs"), or if that is unset, n = 3). Further, for strptime %OS will input seconds including fractional seconds.

The behaviour of other conversion specifications (and even if other character sequences commencing with % are conversion specifications) is system-specific. For output on Windows, a coversion specification is % optionally followed by # and then by a single letter. Any conversion specification which is unimplemented is ignored.

ISOdatetime and ISOdate are convenience wrappers for strptime, that differ only in their defaults and that ISOdate sets a timezone. (For dates without times it would be better to use the "Date" class.)

Value

The format methods and strftime return character vectors representing the time.
strptime turns character representations into an object of class "POSIXlt". The timezone is used to set the isdst component.
ISOdatetime and ISOdate return an object of class "POSIXct".

Note

The default formats follow the rules of the ISO 8601 international standard which expresses a day as "2001-02-28" and a time as "14:01:02" using leading zeroes as here. The ISO form uses no space to separate dates and times.

If the date string does not specify the date completely, the returned answer may be system-specific. The most common behaviour is to assume that unspecified seconds, minutes or hours are zero, and a missing year, month or day is the current one. If it specifies a date incorrectly, reliable implementations will give an error and the date is reported as NA. Unfortunately some common implementations (such as glibc) are unreliable and guess at the intended meaning.

If the timezone specified is invalid on your system, what happens is system-specific but it will probably be ignored.

OS facilities will probably not print years before 1CE (aka 1AD) correctly.

Remember that in most timezones some times do not occur and some occur twice because of transitions to/from summer time. What happens in those cases is OS-specific.

References

International Organization for Standardization (2004, 1988, 1997, ...) ISO 8601. Data elements and interchange formats – Information interchange – Representation of dates and times. For links to versions available on-line see (at the time of writing) http://www.qsl.net/g1smd/isopdf.htm; for information on the current official version, see http://www.iso.org/iso/en/prods-services/popstds/datesandtime.html.

See Also

DateTimeClasses for details of the date-time classes; locales to query or set a locale.

Your system's help pages on strftime and strptime to see how to specify their formats. Windows users will find no help page for strptime: code based on glibc is used (with corrections), so all the conversion specifications described here are supported, but with no alternative number representation nor era available in any locale.

Examples

## locale-specific version of date()
format(Sys.time(), "%a %b %d %X %Y %Z")

## time to sub-second accuracy (if supported by the OS)
format(Sys.time(), "%H:%M:%OS3")

## read in date info in format 'ddmmmyyyy'
## This will give NA(s) in some locales; setting the C locale
## as in the commented lines will overcome this on most systems.
## lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C")
x <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
z <- strptime(x, "%d%b%Y")
## Sys.setlocale("LC_TIME", lct)
z

## read in date/time info in format 'm/d/y h:m:s'
dates <- c("02/27/92", "02/27/92", "01/14/92", "02/28/92", "02/01/92")
times <- c("23:03:20", "22:29:56", "01:03:30", "18:21:03", "16:56:26")
x <- paste(dates, times)
strptime(x, "%m/%d/%y %H:%M:%S")

## time with fractional seconds
z <- strptime("20/2/06 11:16:16.683", "%d/%m/%y %H:%M:%OS")
z # prints without fractional seconds
op <- options(digits.secs=3)
z
options(op)


Split the Elements of a Character Vector

Description

Split the elements of a character vector x into substrings according to the presence of substring split within them.

Usage

strsplit(x, split, extended = TRUE, fixed = FALSE, perl = FALSE)

Arguments

x | character vector, each element of which is to be split. Other inputs, including a factor, will give an error.
split | character vector (or object which can be coerced to such) containing regular expression(s) (unless fixed = TRUE) to use as “split”. If empty matches occur, in particular if split has length 0, x is split into single characters. If split has length greater than 1, it is re-cycled along x.
extended | logical. If TRUE, extended regular expression matching is used, and if FALSE basic regular expressions are used.
fixed | logical. If TRUE match string exactly, otherwise use regular expressions. Has priority over perl and extended.
perl | logical. Should perl-compatible regexps be used? Has priority over extended.

Details

Argument split will be coerced to character, so you will see uses with split = NULL to mean split = character(0), including in the examples below.

Note that spltting into single characters can be done via split=character(0) or split=""; the two are equivalent. The definition of ‘character’ here depends on the locale (and perhaps OS): in a single-byte locale it is a byte, and in a multi-byte locale it is the unit represented by a ‘wide character’ (almost always a Unicode point).

A missing value of split does not split the corresponding element(s) of x at all.

The algorithm applied to each input string is

    repeat {
        if the string is empty
            break.
        if there is a match
            add the string to the left of the match to the output.
            remove the match and all to the left of it.
        else
            add the string to the output.
            break.
    }
Note that this means that if there is a match at the beginning of a (non-empty) string, the first element of the output is "", but if there is a match at the end of the string, the output is the same as with the match removed.

Value

A list of length length(x) the i-th element of which contains the vector of splits of x[i].

Warning

The standard regular expression code has been reported to be very slow when applied to extremely long character strings (tens of thousands of characters or more): the code used when perl = TRUE seems much faster and more reliable for such usages.

The perl = TRUE option is only implemented for single-byte and UTF-8 encodings, and will warn if used in a non-UTF-8 multibyte locale.

See Also

paste for the reverse, grep and sub for string search and manipulation; further nchar, substr.

regular expression for the details of the pattern specification.

Examples

noquote(strsplit("A text I want to display with spaces", NULL)[[1]])

x <- c(as = "asfef", qu = "qwerty", "yuiop[", "b", "stuff.blah.yech")
# split x on the letter e
strsplit(x,"e")

unlist(strsplit("a.b.c", "."))
## [1] "" "" "" "" ""
## Note that 'split' is a regexp!
## If you really want to split on '.', use
unlist(strsplit("a.b.c", "\\."))
## [1] "a" "b" "c"
## or
unlist(strsplit("a.b.c", ".", fixed = TRUE))

## a useful function: rev() for strings
strReverse <- function(x)
        sapply(lapply(strsplit(x, NULL), rev), paste, collapse="")
strReverse(c("abc", "Statistics"))

## get the first names of the members of R-core
a <- readLines(file.path(R.home("doc"),"AUTHORS"))[-(1:8)]
a <- a[(0:2)-length(a)]
(a <- sub(" .*","", a))
# and reverse them
strReverse(a)

## Note that final empty strings are not produced:
strsplit(paste(c("", "a", ""), collapse="#"), split="#")[[1]]
# [1] ""  "a"
## and also an empty string is only produced before a definite match:
strsplit("", " ")[[1]]    # character(0)
strsplit(" ", " ")[[1]]   # [1] ""


Trim Character Strings to Specified Widths

Description

Trim character strings to specified display widths.

Usage

strtrim(x, width)

Arguments

x | a character vector, or an object which can be coerced to a character vector by as.character.
width | Positive integer values: recycled to the length of x.

Details

‘Width’ is interpreted as the display width in a monospaced font. What happens with non-printable characters (such as backspace, tab) is implementation-dependent and may depend on the locale (e.g. they may be included in the count or they may be omitted).

Using this function rather than substr is important when there might be double-width characters in character vectors

Value

A character vector of the same length and with the same attributes as x (after possible coercion).

Examples

strtrim(c("abcdef", "abcdef", "abcdef"), c(1,5,10))


Attribute Specification

Description

structure returns the given object with further attributes set.

Usage

structure(.Data, ...)

Arguments

.Data | an object which will have various attributes attached to it.
... | attributes, specified in tag=value form, which will be attached to data.

Details

Adding a tsp attribute will ensure that the object returned inherits from class "ts", and adding a levels attribute ensures that the returned object is a factor. These conversions are deprecated: they give a warning and will be removed in R 2.5.0.

For historical reasons (these names are used when deparsing), attributes ".Dim", ".Dimnames", ".Names", ".Tsp" and ".Label" are renammed to "dim", "dimnames", "names", "tsp" and "levels".

It is possible to give the same tag more than once, in which case the last value assigned wins. As with other ways of assigning attributes, using tag=NULL removes attribute tag from .Data if it is present.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

attributes, attr.

Examples

structure(1:6, dim = 2:3)


Wrap Character Strings to Format Paragraphs

Description

Each character string in the input is first split into paragraphs (on lines containing whitespace only). The paragraphs are then formatted by breaking lines at word boundaries. The target columns for wrapping lines and the indentation of the first and all subsequent lines of a paragraph can be controlled independently.

Usage

strwrap(x, width = 0.9 * getOption("width"), indent = 0,
        exdent = 0, prefix = "", simplify = TRUE)

Arguments

x | a character vector, or an object which can be converted to a character vector by as.character.
width | a positive integer giving the target column for wrapping lines in the output.
indent | a non-negative integer giving the indentation of the first line in a paragraph.
exdent | a non-negative integer specifying the indentation of subsequent lines in paragraphs.
prefix | a character string to be used as prefix for each line.
simplify | a logical. If TRUE, the result is a single character vector of line text; otherwise, it is a list of the same length as x the elements of which are character vectors of line text obtained from the corresponding element of x. (Hence, the result in the former case is obtained by unlisting that of the latter.)

Details

Whitespace in the input is destroyed. Double spaces after periods (thought as representing sentence ends) are preserved. Currently, possible sentence ends at line breaks are not considered specially.

Indentation is relative to the number of characters in the prefix string.

Examples

## Read in file 'THANKS'.
x <- paste(readLines(file.path(R.home("doc"), "THANKS")), collapse = "\n")
## Split into paragraphs and remove the first three ones
x <- unlist(strsplit(x, "\n[ \t\n]*\n"))[-(1:3)]
## Join the rest
x <- paste(x, collapse = "\n\n")
## Now for some fun:
writeLines(strwrap(x, width = 60))
writeLines(strwrap(x, width = 60, indent = 5))
writeLines(strwrap(x, width = 60, exdent = 5))
writeLines(strwrap(x, prefix = "THANKS> "))

## Note that messages are wrapped AT the target column indicated by
## 'width' (and not beyond it).
## From an R-devel posting by J. Hosking <jh910@juno.com>.
x <- paste(sapply(sample(10, 100, rep=TRUE),
           function(x) substring("aaaaaaaaaa", 1, x)), collapse = " ")
sapply(10:40,
       function(m)
       c(target = m, actual = max(nchar(strwrap(x, m)))))


Subsetting Vectors, Matrices and Data Frames

subset(base) R Documentation

Subsetting Vectors Matrices and Data Frames

Description

Return subsets of vectors, matrices or data frames which meet conditions.

Usage

subset(x, ...)

## Default S3 method:
subset(x, subset, ...)

## S3 method for class 'matrix':
subset(x, subset, select, drop = FALSE, ...)

## S3 method for class 'data.frame':
subset(x, subset, select, drop = FALSE, ...)

Arguments

x | object to be subsetted.
subset | logical expression indicating elements or rows to keep: missing values are taken as false.
select | expression, indicating columns to select from a data frame.
drop | passed on to [ indexing operator.
... | further arguments to be passed to or from other methods.

Details

This is a generic function, with methods supplied for matrices, data frames and vectors (including lists). Packages and users can add further methods.

For ordinary vectors, the result is simply x[subset & !is.na(subset)].

For data frames, the subset argument works on the rows. Note that subset will be evaluated in the data frame, so columns can be referred to (by name) as variables in the expression (see the examples).

The select argument exists only for the methods for data frames and matrices. It works by first replacing column names in the selection expression with the corresponding column numbers in the data frame and then using the resulting integer vector to index the columns. This allows the use of the standard indexing conventions so that for example ranges of columns can be specified easily, or single columns can be dropped (see the examples).

The drop argument is passed on to the indexing method for matrices and data frames: note that the default for matrices is different from that for indexing.

Value

An object similar to x contain just the selected elements (for a vector), rows and columns (for a matrix or data frame), and so on.

Author(s)

Peter Dalgaard and Brian Ripley

See Also

[, transform

Examples

subset(airquality, Temp > 80, select = c(Ozone, Temp))
subset(airquality, Day == 1, select = -Temp)
subset(airquality, select = Ozone:Wind)

with(airquality, subset(Ozone, Temp > 80))

## sometimes requiring a logical 'subset' argument is a nuisance
nm <- rownames(state.x77)
start_with_M <- nm %in% grep("^M", nm, value=TRUE)
subset(state.x77, start_with_M, Illiteracy:Murder)


Substituting and Quoting Expressions

Description

substitute returns the parse tree for the (unevaluated) expression expr, substituting any variables bound in env.

quote simply returns its argument. The argument is not evaluated and can be any R expression.

Usage

substitute(expr, env)
quote(expr)

Arguments

expr | Any syntactically valid R expression
env | An environment or a list object. Defaults to the current evaluation environment.

Details

The typical use of substitute is to create informative labels for data sets and plots. The myplot example below shows a simple use of this facility. It uses the functions deparse and substitute to create labels for a plot which are character string versions of the actual arguments to the function myplot.

Substitution takes place by examining each component of the parse tree as follows: If it is not a bound symbol in env, it is unchanged. If it is a promise object, i.e., a formal argument to a function or explicitly created using delayedAssign(), the expression slot of the promise replaces the symbol. If it is an ordinary variable, its value is substituted, unless env is .GlobalEnv in which case the symbol is left unchanged.

substitute is a primitive function so positional matching is used and names of supplied arguments are ignored.

Value

The mode of the result is generally "call" but may in principle be any type. In particular, single-variable expressions have mode "name" and constants have the appropriate base mode.

Note

Substitute works on a purely lexical basis. There is no guarantee that the resulting expression makes any sense.

Substituting and quoting often causes confusion when the argument is expression(...). The result is a call to the expression constructor function and needs to be evaluated with eval to give the actual expression object.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

missing for argument “missingness”, bquote for partial substitution, sQuote and dQuote for adding quotation marks to strings.

Examples

(s.e <- substitute(expression(a + b), list(a = 1)))  #> expression(1 + b)
(s.s <- substitute( a + b,            list(a = 1)))  #> 1 + b
c(mode(s.e), typeof(s.e)) #  "call", "language"
c(mode(s.s), typeof(s.s)) #   (the same)
# but:
(e.s.e <- eval(s.e))          #>  expression(1 + b)
c(mode(e.s.e), typeof(e.s.e)) #  "expression", "expression"

substitute(x <- x + 1, list(x=1)) # nonsense

myplot <- function(x, y)
    plot(x, y, xlab=deparse(substitute(x)),
         ylab=deparse(substitute(y)))

## Simple examples about lazy evaluation, etc:

f1 <- function(x, y = x)             { x <- x + 1; y }
s1 <- function(x, y = substitute(x)) { x <- x + 1; y }
s2 <- function(x, y) { if(missing(y)) y <- substitute(x); x <- x + 1; y }
a <- 10
f1(a)# 11
s1(a)# 11
s2(a)# a
typeof(s2(a))# "symbol"


Substrings of a Character Vector

Description

Extract or replace substrings in a character vector.

Usage

substr(x, start, stop)
substring(text, first, last = 1000000)
substr(x, start, stop) <- value
substring(text, first, last = 1000000) <- value

Arguments

x, text | a character vector.
start, first | integer. The first element to be replaced.
stop, last | integer. The last element to be replaced.
value | a character vector, recycled if necessary.

Details

substring is compatible with S, with first and last instead of start and stop. For vector arguments, it expands the arguments cyclically to the length of the longest provided none are of zero length.

When extracting, if start is larger than the string length then "" is returned.

For the extraction functions, x or text will be converted to a character vector by as.character if it is not already one.

For the replacement functions, if start is larger than the string length then no replacement is done. If the portion to be replaced is longer than the replacement string, then only the portion the length of the string is replaced.

Value

For substr, a character vector of the same length and with the same attributes as x (after possible coercion).
For substring, a character vector of length the longest of the arguments. This will have names taken from x (if it has any after coercion, repeated as needed), and other attributes copied from x if it is the longest of the arguments).

Note

The S4 version of substring<- ignores last; this version does not.

These functions are often used with nchar to truncate a display. That does not really work (you want to limit the width, not the number of characters, so it would be better to use strtrim), but at least make sure you use nchar(type="c").

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole. (substring.)

See Also

strsplit, paste, nchar.

Examples

substr("abcdef",2,4)
substring("abcdef",1:6,1:6)
## strsplit is more efficient ...

substr(rep("abcdef",4),1:4,4:5)
x <- c("asfef", "qwerty", "yuiop[", "b", "stuff.blah.yech")
substr(x, 2, 5)
substring(x, 2, 4:6)

substring(x, 2) <- c("..", "+++")
x


Sum of Vector Elements

Description

sum returns the sum of all the values present in its arguments.

Usage

sum(..., na.rm = FALSE)

Arguments

... | numeric or complex or logical vectors.
na.rm | logical. Should missing values be removed?

Details

This is a generic function: methods can be defined for it directly or via the Summary group generic. For this to work properly, the arguments ... should be unnamed, and dispatch is on the first argument.

If na.rm is FALSE an NA value in any of the arguments will cause a value of NA to be returned, otherwise NA values are ignored.

Logical true values are regarded as one, false values as zero. For historical reasons, NULL is accepted and treated as if it were integer(0).

Value

The sum. If all of ... are of type integer or logical, then the sum is integer, and in that case the result will be NA (with a warning) if integer overflow occurs. Otherwise it is a length-one numeric or complex vector.
NB: the sum of an empty set is zero, by definition.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.


Object Summaries

Description

summary is a generic function used to produce result summaries of the results of various model fitting functions. The function invokes particular methods which depend on the class of the first argument.

Usage

summary(object, ...)

## Default S3 method:
summary(object, ..., digits = max(3, getOption("digits")-3))
## S3 method for class 'data.frame':
summary(object, maxsum = 7,
       digits = max(3, getOption("digits")-3), ...)

## S3 method for class 'factor':
summary(object, maxsum = 100, ...)

## S3 method for class 'matrix':
summary(object, ...)

Arguments

object | an object for which a summary is desired.
maxsum | integer, indicating how many levels should be shown for factors.
digits | integer, used for number formatting with signif() (for summary.default) or format() (for summary.data.frame).
... | additional arguments affecting the summary produced.

Details

For factors, the frequency of the first maxsum - 1 most frequent levels is shown, where the less frequent levels are summarized in "(Others)" (resulting in maxsum frequencies).

The functions summary.lm and summary.glm are examples of particular methods which summarise the results produced by lm and glm.

Value

The form of the value returned by summary depends on the class of its argument. See the documentation of the particular methods for details of what is produced by that method.

References

Chambers, J. M. and Hastie, T. J. (1992) Statistical Models in S. Wadsworth & Brooks/Cole.

See Also

anova, summary.glm, summary.lm.

Examples

summary(attenu, digits = 4) #-> summary.data.frame(...), default precision
summary(attenu $ station, maxsum = 20) #-> summary.factor(...)

lst <- unclass(attenu$station) > 20 # logical with NAs
## summary.default() for logicals -- different from *.factor:
summary(lst)
summary(as.factor(lst))


Singular Value Decomposition of a Matrix

Description

Compute the singular-value decomposition of a rectangular matrix.

Usage

svd(x, nu = min(n, p), nv = min(n, p), LINPACK = FALSE)

La.svd(x, nu = min(n, p), nv = min(n, p))

Arguments

x | a real or complex matrix whose SVD decomposition is to be computed.
nu | the number of left singular vectors to be computed. This must between 0 and n = nrow(x).
nv | the number of right singular vectors to be computed. This must be between 0 and p = ncol(x).
LINPACK | logical. Should LINPACK be used (for compatibility with R < 1.7.0)? In this case nu must be 0, nrow(x) or ncol(x).

Details

The singular value decomposition plays an important role in many statistical techniques. svd and La.svd provide two slightly different interfaces. The main functions used are the LAPACK routines DGESDD and ZGESVD; svd(LINPACK = TRUE) provides an interface to the LINPACK routine DSVDC, purely for backwards compatibility.

Computing the singular vectors is the slow part for large matrices. The computation will be more efficient if nu <= min(n, p) and nv <= min(n, p), and even more efficient if one or both are zero.

Unsuccessful results from the underlying LAPACK code will result in an error giving a positive error code: these can only be interpreted by detailed study of the FORTRAN code.

Value

The SVD decomposition of the matrix as computed by LAPACK/LINPACK,

X = U D V',

where U and V are orthogonal, V' means V transposed, and D is a diagonal matrix with the singular values D[i,i]. Equivalently, D = U' X V, which is verified in the examples, below.
The returned value is a list with components

d | a vector containing the singular values of x, of length min(n, p).
u | a matrix whose columns contain the left singular vectors of x, present if nu > 0. Dimension c(n, nu).
v | a matrix whose columns contain the right singular vectors of x, present if nv > 0. Dimension c(p, nv).

For La.svd the return value replaces v by vt, the (conjugated if complex) transpose of v.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Dongarra, J. J., Bunch, J. R., Moler, C. B. and Stewart, G. W. (1978) LINPACK Users Guide. Philadelphia: SIAM Publications.

Anderson. E. and ten others (1999) LAPACK Users' Guide. Third Edition. SIAM.
Available on-line at http://www.netlib.org/lapack/lug/lapack_lug.html.

See Also

eigen, qr.

Examples

hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
X <- hilbert(9)[,1:6]
(s <- svd(X))
D <- diag(s$d)
s$u %*% D %*% t(s$v) #  X = U D V'
t(s$u) %*% X %*% s$v #  D = U' X V


Sweep out Array Summaries

Description

Return an array obtained from an input array by sweeping out a summary statistic.

Usage

sweep(x, MARGIN, STATS, FUN="-", ...)

Arguments

x | an array.
MARGIN | a vector of indices giving the extents of x which correspond to STATS.
STATS | the summary statistic which is to be swept out.
FUN | the function to be used to carry out the sweep. In the case of binary operators such as "/" etc., the function name must backquoted or quoted. (FUN is found by a call to match.fun.)
... | optional arguments to FUN.

Value

An array with the same shape as x, but with the summary statistics swept out.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

apply on which sweep used to be based; scale for centering and scaling.

Examples

require(stats) # for median
med.att <- apply(attitude, 2, median)
sweep(data.matrix(attitude), 2, med.att)# subtract the column medians


Select One of a List of Alternatives

Description

switch evaluates EXPR and accordingly chooses one of the further arguments (in ...).

Usage

switch(EXPR, ...)

Arguments

EXPR | an expression evaluating to a number or a character string.
... | the list of alternatives, given explicitly.

Details

If the value of EXPR is an integer between 1 and nargs()-1 then the corresponding element of ... is evaluated and the result returned.

If EXPR returns a character string then that string is used to match the names of the elements in .... If there is an exact match then that element is evaluated and returned if there is one, otherwise the next element is chosen, e.g., switch("cc", a=1, cc=, d=2) evaluates to 2.

In the case of no match, if there's a further argument in switch that one is returned, otherwise NULL.

Warning

Beware of partial matching: an alternative E = foo will match the first argument EXPR unless that is named. See the examples for good practice in naming the first argument.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Examples

require(stats)
centre <- function(x, type) {
  switch(type,
        mean = mean(x),
        median = median(x),
        trimmed = mean(x, trim = .1))
}
x <- rcauchy(10)
centre(x, "mean")
centre(x, "median")
centre(x, "trimmed")

ccc <- c("b","QQ","a","A","bb")
for(ch in ccc)
    cat(ch,":",switch(EXPR = ch, a=1,     b=2:3), "\n")
for(ch in ccc)
    cat(ch,":",switch(EXPR = ch, a=, A=1, b=2:3, "Otherwise: last"),"\n")

## Numeric EXPR don't allow an 'otherwise':
for(i in c(-1:3,9))  print(switch(i, 1,2,3,4))


Operator Syntax and Precedence

Description

Outlines R syntax and gives the precedence of operators

Details

The following unary and binary operators are defined. They are listed in precedence groups, from highest to lowest.
[ [[ | indexing
:: ::: | access variables in a name space
$ @ | component / slot extraction
^ | exponentiation (right to left)
- + | unary minus and plus
: | sequence operator
%any% | special operators
* / | multiply, divide
+ - | (binary) add, subtract
< > <= >= == != | ordering and comparison
! | negation
& && | and
| || | or
~ | as in formulae
-> ->> | rightwards assignment
= | assignment (right to left)
<- <<- | assignment (right to left)
? | help (unary and binary)

Within an expression operators of equal precedence are evaluated from left to right except where indicated.

The links in the See Also section covers most other aspects of the basic syntax.

Note

There are substantial precedence differences between R and S. In particular, in S ? has the same precedence as (binary) + - and & && | || have equal precedence.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

Arithmetic, Comparison, Control, Extract, Logic, NumericConstants, Paren, Quotes.

The R Language Definition manual.


Extract System and User Information

Description

Reports system and user information.

Usage

Sys.info()

Details

This function is not implemented on all R platforms, and returns NULL when not available. Where possible it is based on POSIX system calls.

Sys.info() returns details of the platform R is running on, whereas R.version gives details of the platform R was built on: they may well be different.

Value

A character vector with fields

sysname | The operating system.
release | The OS release.
version | The OS version.
nodename | A name by which the machine is known on the network (if any).
machine | A concise description of the hardware.
login | The user's login name, or "unknown" if it cannot be ascertained.
user | The name of the real user ID, or "unknown" if it cannot be ascertained.

The information is obtained from Windows system calls. It is likely to be most complete on Windows NT/2000/XP systems.

Note

The meaning of OS “release” and “version” is highly system-dependent and there is no guarantee that the node or login or user names will be what you might reasonably expect. (In particular on some Linux distributions the login name is unknown from sessions with re-directed inputs.)

See Also

.Platform, and R.version.

Examples

Sys.info()
## An alternative (and probably better) way to get the login name on Unix
Sys.getenv("LOGNAME")


Functions to Access the Function Call Stack

Description

These functions provide access to environments (“frames” in S terminology) associated with functions further up the calling stack.

Usage

sys.call(which = 0)
sys.frame(which = 0)
sys.nframe()
sys.function(which = 0)
sys.parent(n = 1)

sys.calls()
sys.frames()
sys.parents()
sys.on.exit()
sys.status()
parent.frame(n = 1)

Arguments

which | the frame number if non-negative, the number of frames to go back if negative.
n | the number of generations to go back. (See the Details section.)

Details

.GlobalEnv is given number 0 in the list of frames. Each subsequent function evaluation increases the frame stack by 1 and the call, function definition and the environment for evaluation of that function are returned by sys.call, sys.function and sys.frame with the appropriate index.

sys.call, sys.frame and sys.function accept integer values for the argument which. Non-negative values of which are frame numbers whereas negative values are counted back from the frame number of the current evaluation.

The parent frame of a function evaluation is the environment in which the function was called. It is not necessarily numbered one less than the frame number of the current evaluation, nor is it the environment within which the function was defined. sys.parent returns the number of the parent frame if n is 1 (the default), the grandparent if n is 2, and so on.

sys.nframe returns an integer, the number of the current frame as described in the first paragraph.

sys.calls and sys.frames give a pairlist of all the active calls and frames, repectively, and sys.parents returns an integer vector of indices of the parent frames of each of those frames.

Notice that even though the sys.xxx functions (except sys.status) are interpreted, their contexts are not counted nor are they reported. There is no access to them.

sys.status() returns a list with components sys.calls, sys.parents and sys.frames, the results of calls to those three functions (which this will include the call to sys.status: see the first example).

sys.on.exit() returns the expression stored for use by on.exit in the function currently being evaluated. (Note that this differs from S, which returns a list of expressions for the current frame and its parents.)

parent.frame(n) is a convenient shorthand for sys.frame(sys.parent(n)) (implemented slightly more efficiently).

Value

sys.call returns a call, sys.function a function definition, and sys.frame, sys.parent and parent.frame return an environment.
For the other functions, see the Details section.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole. (not parent.frame.)

See Also

eval for a usage of sys.frame and parent.frame.

Examples

## Note: the first two examples will give different results
## if run by example().
ff <- function(x) gg(x)
gg <- function(y) sys.status()
str(ff(1))

gg <- function(y) {
    ggg <- function() {
        cat("current frame is", sys.nframe(), "\n")
        cat("parents are", sys.parents(), "\n")
        print(sys.function(0)) # ggg
        print(sys.function(2)) # gg
    }
    if(y > 0) gg(y-1) else ggg()
}
gg(3)

t1 <- function() {
  aa <- "here"
  t2 <- function() {
    ## in frame 2 here
    cat("current frame is", sys.nframe(), "\n")
    str(sys.calls()) ## list with two components t1() and t2()
    cat("parents are frame numbers", sys.parents(), "\n") ## 0 1
    print(ls(envir=sys.frame(-1))) ## [1] "aa" "t2"
    invisible()
  }
  t2()
}
t1()

test.sys.on.exit <- function() {
  on.exit(print(1))
  ex <- sys.on.exit()
  str(ex)
  cat("exiting...\n")
}
test.sys.on.exit()
## gives 'language print(1)', prints 1 on exit

## An example where the parent is not the next frame up the stack
## since method dispatch uses a frame.
as.double.foo <- function(x)
{
    str(sys.calls())
    print(sys.frames())
    print(sys.parents())
    print(sys.frame(-1)); print(parent.frame())
    x
}
t2 <- function(x) as.double(x)
a <- structure(pi, class = "foo")
t2(a)


Suspend Execution for a Time Interval

Description

Suspend execution of R expressions for a given number of seconds

Usage

Sys.sleep(time)

Arguments

time The time interval to suspend execution for, in seconds.

Details

Using this function allows R to be given very low priority and hence not to interfere with more important foreground tasks. A typical use is to allow a process launched from R to set itself up and read its input files before R execution is resumed.

The intention is that this function suspends execution of R expressions but wakes the process up often enough to respond to GUI events, typically every 0.5 seconds.

There is no guarantee that the process will sleep for the whole of the specified interval, and it may well take slightly longer in real time to resume execution. The resolution of the time interval is system-dependent, but will normally be down to 0.02 secs or better. (On modern Unix-alikes it will be better than 1ms.)

Value

Invisible NULL.

Note

This function may not be implemented on all systems.

Examples

testit <- function(x)
{
    p1 <- proc.time()
    Sys.sleep(x)
    proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)


Parse and Evaluate Expressions from a File

Description

Parses expressions in the given file, and then successively evaluates them in the specified environment.

Usage

sys.source(file, envir = baseenv(), chdir = FALSE,
           keep.source = getOption("keep.source.pkgs"))

Arguments

file | a character string naming the file to be read from
envir | an R object specifying the environment in which the expressions are to be evaluated. May also be a list or an integer. The default value NULL corresponds to evaluation in the base environment. This is probably not what you want; you should typically supply an explicit envir argument.
chdir | logical; if TRUE, the R working directory is changed to the directory containing file for evaluating.
keep.source | logical. If TRUE, functions “keep their source” including comments, see options(keep.source = *) for more details.

Details

For large files, keep.source = FALSE may save quite a bit of memory. In order for the code being evaluated to use the correct environment (for example, in global assignments), source code in packages should call topenv(), which will return the namespace, if any, the environment set up by sys.source, or the global environment if a saved image is being used.

See Also

source, and library which uses sys.source.


Get Current Date, Time and Timezone

Sys.time(base) R Documentation

Get Current Date Time and Timezone

Description

Sys.time and Sys.Date returns the system's idea of the current date with and without time, and Sys.timezone returns the current time zone.

Usage

Sys.time()
Sys.Date()
Sys.timezone()

Details

Sys.time returns an absolute date-time value which can be converted in various time zones and may return different days.

Sys.Date returns the day in the current timezone.

Value

Sys.time returns an object of class "POSIXct" (see DateTimeClasses). On some systems it will have sub-second accuracy, but on others it will increment in seconds. On Windows, it increments in clock ticks (1/60 of a second) reported to millisecond accuracy.
Sys.Date returns an object of class "Date" (see Date).
Sys.timezone returns an OS-specific character string, possibly an empty string. It may be possible to set the timezone via the environment variable "TZ": see as.POSIXlt. Windows is notorious for naming its timezones differently from the official names.

See Also

date for the system time in a fixed-format character string; the elapsed time component of proc.time for possibly finer resolution in changes in time.

Examples

Sys.time()
## print with possibly greater accuracy:
op <- options(digits.secs=6)
Sys.time()
options(op)

## locale-specific version of date()
format(Sys.time(), "%a %b %d %X %Y")

Sys.Date()

Sys.timezone()


Invoke a System Command

Description

system invokes the system command specified by command.

Usage

system(command, intern = FALSE, wait = TRUE, input = NULL,
       show.output.on.console = FALSE,
       minimized = FALSE, invisible = FALSE)

Arguments

command | the system command to be invoked, as a string.
intern | a logical, indicates whether to make the output of the command an R object.
wait | should the R interpreter wait for the command to finish? The default is to wait, and the interpreter will always wait if intern = TRUE.
input | if a character vector is supplied, this is copied one string per line to a temporary file, and the standard input of command is redirected to the file.
show.output.on.console | a logical, indicates whether to capture the output of the command and show it on the R console (not used by Rterm, which captures the output unless wait is false).
minimized | a logical, indicates whether the command window should be initially displayed as a minimized window.
invisible | a logical, indicates whether the command window should be visible on the screen.

Details

cmd is parsed as a command plus arguments separated by spaces. So if the path to the command contains spaces, it must be (double-)quoted. See the examples. (Note: a Windows path name cannot contain a double quote, so we do not need to worry about escaping embedded quotes.)

The command is run directly as a Windows command by the Windows API call CreateProcess: extensions of .exe, .com, .cmd and .bat are tried in turn if none is supplied. (To use DOS internal commands use paste(Sys.getenv("COMSPEC"),"/c",cmd).) The search path for command may be system-dependent: it will include the R bin directory, the working directory and the Windows system directories before PATH.

Precisely what is seen by the user depends on whether Rgui or Rterm is being used. For Rgui a new console will always be used, so a commands window will appear for the duration of console applications unless invisible is true. For Rterm a separate commands window will appear for console applications only if wait = FALSE.

unix is a deprecated alternative, available for backwards compatibility.

Value

If intern = TRUE, a character vector giving the output of the command, one line per character string. If the command could not be run or gives an error a R error is generated. (Output lines of more than 8095 characters will be split.)
If intern = FALSE, the return value is an error code, given the invisible attribute (so needs to be printed explicitly). If the command could not be run for any reason, the value is -1 and an R warning is generated. Otherwise if wait = TRUE the value is the error code returned by the command, and if wait = FALSE it is the zero (the conventional success value),
If intern = FALSE and show.output.on.console = TRUE the text output from a command that is a console application will appear in the R console (Rgui) or the window running R (Rterm).

Warning

The command cannot be interrupted by the R process.

Do not run console applications that require user input from Rgui setting intern = TRUE and/or show.output.on.console = TRUE. They will not work, may hang and then will probably hang Rgui too.

See Also

shell or shell.exec for a less raw interface.

Examples

# launch an editor, wait for it to quit
## Not run: system("notepad myfile.txt")
# launch a Windows 9x process monitor (from Win9x KernelToys)
## Not run: system("wintop", wait = FALSE)
# launch your favourite shell:
## Not run: system(Sys.getenv("COMSPEC"))
## Not run:
## note the two sets of quotes here:
system(paste('"c:/Program Files/Mozilla Firefox/firefox.exe"',
             '-url cran.r-project.org'), wait = FALSE)
## End(Not run)


Find Names of R System Files

Description

Finds the full file names of files in packages etc.

Usage

system.file(..., package = "base", lib.loc = NULL)

Arguments

... | character strings, specifying subdirectory and file(s) within some package. The default, none, returns the root of the package. Wildcards are not supported.
package | a character string with the name of a single package. An error occurs if more than one package name is given.
lib.loc | a character vector with path names of R libraries, or NULL. The default value of NULL corresponds to all libraries currently known. If the default is used, the loaded packages are searched before the libraries.

Value

A character vector of positive length, containing the file names that matched ..., or the empty string, "", if none matched. If matching the root of a package, there is no trailing separator.
As a special case, system.file() gives the root of the base package only.

See Also

list.files

Examples

system.file()                  # The root of the 'base' package
system.file(package = "stats") # The root of package 'stats'
system.file("INDEX")
system.file("help", "AnIndex", package = "splines")


CPU Time Used

Description

Return CPU (and other) times that expr used.

Usage

system.time(expr, gcFirst = TRUE)
unix.time(expr, gcFirst = TRUE)

Arguments

expr | Valid R expression to be “timed”
gcFirst | Logical - should a garbage collection be performed immediately before the timing? Default is TRUE.

Details

system.time calls the builtin proc.time, evaluates expr, and then calls proc.time once more, returning the difference between the two proc.time calls.

unix.time is an alias of system.time, for compatibility reasons.

Timings of evaluations of the same expression can vary considerably depending on whether the evaluation triggers a garbage collection. When gcFirst is TRUE a garbage collection (gc) will be performed immediately before the evaluation of expr. This will usually produce more consistent timings.

Value

A numeric vector of length 5 containing the user cpu, system cpu, elapsed, subproc1, subproc2 times. The subproc times are the user and system cpu time used by child processes (and so are usually zero).
On Windows the subproc times are not available and so are always NA. The first two components are not available on Windows 9x, and so are reported as NA; they do return real values on NT-based versions of Windows.
The resolution of the times will be system-specific; see proc.time for details.

See Also

proc.time, time which is for time series.

Examples

require(stats)
system.time(for(i in 1:100) mad(runif(1000)))
## Not run:
exT <- function(n = 1000) {
  # Purpose: Test if system.time works ok;   n: loop size
  system.time(for(i in 1:n) x <- mean(rt(1000, df=4)))
}
#-- Try to interrupt one of the following (using Ctrl-C / Escape):
exT()                 #- about 3 secs on a 1GHz PIII
system.time(exT())    #~ +/- same
## End(Not run)


Matrix Transpose

Description

Given a matrix or data.frame x, t returns the transpose of x.

Usage

t(x)

Arguments

x a matrix or data frame, typically.

Details

This is a generic function for which methods can be written. The description here applies to the default and "data.frame" methods.

A data frame is first coerced to a matrix: see as.matrix. When x is a vector, it is treated as “column”, i.e., the result is a 1-row matrix.

Value

A matrix, with dim and dimnames constructed appropriately from those of x, and other attributes except names copied across.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

aperm for permuting the dimensions of arrays.

Examples

a <- matrix(1:30, 5,6)
ta <- t(a) ##-- i.e.,  a[i, j] == ta[j, i] for all i,j :
for(j in seq(ncol(a)))
  if(! all(a[, j] == ta[j, ])) stop("wrong transpose")


Cross Tabulation and Table Creation

Description

table uses the cross-classifying factors to build a contingency table of the counts at each combination of factor levels.

Usage

table(..., exclude = c(NA, NaN), dnn = list.names(...),
      deparse.level = 1)
as.table(x, ...)
is.table(x)

## S3 method for class 'table':
as.data.frame(x, row.names = NULL, ...,
              responseName = "Freq")

Arguments

... | objects which can be interpreted as factors (including character strings), or a list (or data frame) whose components can be so interpreted. (For as.table and as.data.frame, arguments passed to specific methods.)
exclude | values to use in the exclude argument of factor when interpreting non-factor objects; if specified, levels to remove from all factors in ....
dnn | the names to be given to the dimensions in the result (the dimnames names).
deparse.level | controls how the default dnn is constructed. See details.
x | an arbitrary R object, or an object inheriting from class "table" for the as.data.frame method.
row.names | a character vector giving the row names for the data frame.
responseName | The name to be used for the column of table entries, usually counts.

Details

If the argument dnn is not supplied, the internal function list.names is called to compute the ‘dimname names’. If the arguments in ... are named, those names are used. For the remaining arguments, deparse.level = 0 gives an empty name, deparse.level = 1 uses the supplied argument if it is a symbol, and deparse.level = 2 will deparse the argument.

Only when exclude is specified (i.e., not by default), will table drop levels of factor arguments potentially.

Value

table() returns a contingency table, an object of class "table", an array of integer values.
There is a summary method for objects created by table or xtabs, which gives basic information and performs a chi-squared test for independence of factors (note that the function chisq.test currently only handles 2-d tables).
as.table and is.table coerce to and test for contingency table, respectively.
The as.data.frame method for objects inheriting from class "table" can be used to convert the array-based representation of a contingency table to a data frame containing the classifying factors and the corresponding entries (the latter as component named by responseName). This is the inverse of xtabs.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

Use ftable for printing (and more) of multidimensional tables. margin.table, prop.table, addmargins.

Examples

require(stats) # for rpois and xtabs
## Simple frequency distribution
table(rpois(100,5))
## Check the design:
with(warpbreaks, table(wool, tension))
table(state.division, state.region)

# simple two-way contingency table
with(airquality, table(cut(Temp, quantile(Temp)), Month))

a <- letters[1:3]
table(a, sample(a))                    # dnn is c("a", "")
table(a, sample(a), deparse.level = 0) # dnn is c("", "")
table(a, sample(a), deparse.level = 2) # dnn is c("a", "sample(a)")

## xtabs() <-> as.data.frame.table() :
UCBAdmissions ## already a contingency table
DF <- as.data.frame(UCBAdmissions)
class(tab <- xtabs(Freq ~ ., DF)) # xtabs & table
## tab *is* "the same" as the original table:
all(tab == UCBAdmissions)
all.equal(dimnames(tab), dimnames(UCBAdmissions))

a <- rep(c(NA, 1/0:3), 10)
table(a)
table(a, exclude=NULL)
b <- factor(rep(c("A","B","C"), 10))
table(b)
table(b, exclude="B")
d <- factor(rep(c("A","B","C"), 10), levels=c("A","B","C","D","E"))
table(d, exclude="B")
print(table(b,d), zero.print = ".")

## NA counting:
is.na(d) <- 3:4
d <- factor(d, exclude=NULL)
d[1:7]
table(d, exclude = NULL)


Tabulation for Vectors

Description

tabulate takes the integer-valued vector bin and counts the number of times each integer occurs in it.

Usage

tabulate(bin, nbins = max(1, bin))

Arguments

bin | a numeric vector (of positive integers), or a factor.
nbins | the number of bins to be used.

Details

tabulate is used as the basis of the table function.

If bin is a factor, its internal integer representation is tabulated.

If the elements of bin are numeric but not integers, they are truncated to the nearest integer.

Value

An integer vector (without names). There is a bin for each of the values 1, ..., nbins; values outside that range are (silently) ignored.

See Also

table, factor.

Examples

tabulate(c(2,3,5))
tabulate(c(2,3,3,5), nbins = 10)
tabulate(c(-2,0,2,3,3,5))  # -2 and 0 are ignored
tabulate(c(-2,0,2,3,3,5), nbins = 3)
tabulate(factor(letters[1:10]))


Apply a Function Over a “Ragged” Array

Description

Apply a function to each cell of a ragged array, that is to each (non-empty) group of values given by a unique combination of the levels of certain factors.

Usage

tapply(X, INDEX, FUN = NULL, ..., simplify = TRUE)

Arguments

X | an atomic object, typically a vector.
INDEX | list of factors, each of same length as X.
FUN | the function to be applied. In the case of functions like +, %*%, etc., the function name must be quoted. If FUN is NULL, tapply returns a vector which can be used to subscript the multi-way array tapply normally produces.
... | optional arguments to FUN.
simplify | If FALSE, tapply always returns an array of mode "list". If TRUE (the default), then if FUN always returns a scalar, tapply returns an array with the mode of the scalar.

Value

When FUN is present, tapply calls FUN for each cell that has any data in it. If FUN returns a single atomic value for each cell (e.g., functions mean or var) and when simplify is TRUE, tapply returns a multi-way array containing the values. The array has the same number of dimensions as INDEX has components; the number of levels in a dimension is the number of levels (nlevels()) in the corresponding component of INDEX.
Note that contrary to S, simplify = TRUE always returns an array, possibly 1-dimensional.
If FUN does not return a single atomic value, tapply returns an array of mode list whose components are the values of the individual calls to FUN, i.e., the result is a list with a dim attribute.
Note that optional arguments to FUN supplied by the ... argument are not divided into cells. It is therefore inappropriate for FUN to expect additional arguments with the same length as X.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

the convenience functions by and aggregate (using tapply); apply, lapply with its versions sapply and mapply.

Examples

require(stats)
groups <- as.factor(rbinom(32, n = 5, p = .4))
tapply(groups, groups, length) #- is almost the same as
table(groups)

## contingency table from data.frame : array with named dimnames
tapply(warpbreaks$breaks, warpbreaks[,-1], sum)
tapply(warpbreaks$breaks, warpbreaks[, 3, drop = FALSE], sum)

n <- 17; fac <- factor(rep(1:3, len = n), levels = 1:5)
table(fac)
tapply(1:n, fac, sum)
tapply(1:n, fac, sum, simplify = FALSE)
tapply(1:n, fac, range)
tapply(1:n, fac, quantile)

## example of ... argument: find quarterly means
tapply(presidents, cycle(presidents), mean, na.rm = TRUE)

ind <- list(c(1, 2, 2), c("A", "A", "B"))
table(ind)
tapply(1:3, ind) #-> the split vector
tapply(1:3, ind, sum)


Add or remove a top-level task callback

Description

addTaskCallback registers an R function that is to be called each time a top-level task is completed.

removeTaskCallback un-registers a function that was registered earlier via addTaskCallback.

These provide low-level access to the internal/native mechanism for managing task-completion actions. One can use taskCallbackManager at the S-language level to manage S functions that are called at the completion of each task. This is easier and more direct.

Usage

addTaskCallback(f, data = NULL, name = character(0))
removeTaskCallback(id)

Arguments

f | the function that is to be invoked each time a top-level task is successfully completed. This is called with 5 or 4 arguments depending on whether data is specified or not, respectively. The return value should be a logical value indicating whether to keep the callback in the list of active callbacks or discard it.
data | if specified, this is the 5-th argument in the call to the callback function f.
id | a string or an integer identifying the element in the internal callback list to be removed. Integer indices are 1-based, i.e the first element is 1. The names of currently registered handlers is available using getTaskCallbackNames and is also returned in a call to addTaskCallback.
name | character: names to be used.

Details

Top-level tasks are individual expressions rather than entire lines of input. Thus an input line of the form expression1 ; expression2 will give rise to 2 top-level tasks.

A top-level task callback is called with the expression for the top-level task, the result of the top-level task, a logical value indicating whether it was successfully completed or not (always TRUE at present), and a logical value indicating whether the result was printed or not. If the data argument was specified in the call to addTaskCallback, that value is given as the fifth argument.

The callback function should return a logical value. If the value is FALSE, the callback is removed from the task list and will not be called again by this mechanism. If the function returns TRUE, it is kept in the list and will be called on the completion of the next top-level task.

Value

addTaskCallback returns an integer value giving the position in the list of task callbacks that this new callback occupies. This is only the current position of the callback. It can be used to remove the entry as long as no other values are removed from earlier positions in the list first.
removeTaskCallback returns a logical value indicating whether the specified element was removed. This can fail (i.e., return FALSE) if an incorrect name or index is given that does not correspond to the name or position of an element in the list.

Note

This is an experimental feature and the interface may be changed in the future.

There is also C-level access to top-level task callbacks to allow C routines rather than R functions be used.

See Also

getTaskCallbackNames taskCallbackManager http://developer.r-project.org/TaskHandlers.pdf

Examples

 times <- function(total = 3, str="Task a") {
   ctr <- 0

   function(expr, value, ok, visible) {
    ctr <<- ctr + 1
    cat(str, ctr, "\n")
    if(ctr == total) {
      cat("handler removing itself\n")
    }
    return(ctr < total)
   }
 }

 # add the callback that will work for
 # 4 top-level tasks and then remove itself.
 n <- addTaskCallback(times(4))

 # now remove it, assuming it is still first in the list.
 removeTaskCallback(n)

## Not run:
# There is no point in running this
# as
 addTaskCallback(times(4))

 sum(1:10)
 sum(1:10)
 sum(1:10)
 sum(1:10)
 sum(1:10)
## End(Not run)


Create an R-level task callback manager

Description

This provides an entirely S-language mechanism for managing callbacks or actions that are invoked at the conclusion of each top-level task. Essentially, we register a single R function from this manager with the underlying, native task-callback mechanism and this function handles invoking the other R callbacks under the control of the manager. The manager consists of a collection of functions that access shared variables to manage the list of user-level callbacks.

Usage

taskCallbackManager(handlers = list(), registered = FALSE,
                    verbose = FALSE)

Arguments

handlers | this can be a list of callbacks in which each element is a list with an element named "f" which is a callback function, and an optional element named "data" which is the 5-th argument to be supplied to the callback when it is invoked. Typically this argument is not specified, and one uses add to register callbacks after the manager is created.
registered | a logical value indicating whether the evaluate function has already been registered with the internal task callback mechanism. This is usually FALSE and the first time a callback is added via the add function, the evaluate function is automatically registered. One can control when the function is registered by specifying TRUE for this argument and calling addTaskCallback manually.
verbose | a logical value, which if TRUE, causes information to be printed to the console about certain activities this dispatch manager performs. This is useful for debugging callbacks and the handler itself.

Value

A list containing 6 functions:

add | register a callback with this manager, giving the function, an optional 5-th argument, an optional name by which the callback is stored in the list, and a register argument which controls whether the evaluate function is registered with the internal C-level dispatch mechanism if necessary.
remove | remove an element from the manager's collection of callbacks, either by name or position/index.
evaluate | the ‘real’ callback function that is registered with the C-level dispatch mechanism and which invokes each of the R-level callbacks within this manager's control.
suspend | a function to set the suspend state of the manager. If it is suspended, none of the callbacks will be invoked when a task is completed. One sets the state by specifying a logical value for the status argument.
register | a function to register the evaluate function with the internal C-level dispatch mechanism. This is done automatically by the add function, but can be called manually.
callbacks | returns the list of callbacks being maintained by this manager.

Note

This is an experimental feature and the interface may be changed in the future.

See Also

addTaskCallback, removeTaskCallback, getTaskCallbackNames\ http://developer.r-project.org/TaskHandlers.pdf

Examples

# create the manager
h <- taskCallbackManager()

# add a callback
h$add(function(expr, value, ok, visible) {
                       cat("In handler\n")
                       return(TRUE)
                     }, name = "simpleHandler")

# look at the internal callbacks.
getTaskCallbackNames()

# look at the R-level callbacks
names(h$callback())

getTaskCallbackNames()
removeTaskCallback("R-taskCallbackManager")


Query the names of the current internal top-level task callbacks

Description

This provides a way to get the names (or identifiers) for the currently registered task callbacks that are invoked at the conclusion of each top-level task. These identifiers can be used to remove a callback.

Usage

getTaskCallbackNames()

Value

A character vector giving the name for each of the registered callbacks which are invoked when a top-level task is completed successfully. Each name is the one used when registering the callbacks and returned as the in the call to addTaskCallback.

Note

One can use taskCallbackManager to manage user-level task callbacks, i.e., S-language functions, entirely within the S language and access the names more directly.

See Also

addTaskCallback, removeTaskCallback, taskCallbackManager\ http://developer.r-project.org/TaskHandlers.pdf

Examples

 n <- addTaskCallback(function(expr, value, ok, visible) {
                        cat("In handler\n")
                        return(TRUE)
                      }, name = "simpleHandler")

 getTaskCallbackNames()

   # now remove it by name
 removeTaskCallback("simpleHandler")

 h <- taskCallbackManager()
 h$add(function(expr, value, ok, visible) {
                        cat("In handler\n")
                        return(TRUE)
                      }, name = "simpleHandler")
 getTaskCallbackNames()
 removeTaskCallback("R-taskCallbackManager")


Create Names for Temporary Files

Description

tempfile returns a vector of character strings which can be used as names for temporary files.

Usage

tempfile(pattern = "file", tmpdir = tempdir())
tempdir()

Arguments

pattern | a non-empty character vector giving the initial part of the name.
tmpdir | a non-empty character vector giving the directory name

Details

If pattern has length greater than one then the result is of the same length giving a temporary file name for each component of pattern.

The names are very likely to be unique among calls to tempfile in an R session and across simultaneous R sessions. The filenames are guaranteed not to be currently in use.

The file name is made of the pattern and a random suffix in hex. By default, the filenames will be in the directory given by tempdir(). This will be a subdirectory of the temporary directory found by the following rule. The environment variables TMPDIR, TMP and TEMP are checked in turn and the first found which points to a writable directory is used: if none succeeds the value of R_USER (see Rconsole) is used. If the path to the directory contains a space in any of the components, the path returned will use the shortnames version of the path.

Value

For tempfile a character vector giving the names of possible (temporary) files. Note that no files are generated by tempfile.
For tempdir, the path of the per-session temporary directory.
Both will use backslash as the path separator.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

unlink for deleting files.

Examples

tempfile(c("ab", "a b c"))   # give file name with spaces in!

tempdir() # working on all platforms with quite platform dependent result


Text Connections

Description

Input and output text connections.

Usage

textConnection(object, open = "r", local = FALSE)

textConnectionValue(con)

Arguments

object | character. A description of the connection. For an input this is an R character vector object, and for an output connection the name for the R character vector to receive the output, or NULL (for none).
open | character. Either "r" (or equivalently "") for an input connection or "w" or "a" for an output connection.
local | logical. Used only for output connections. If TRUE, output is assigned to a variable in the calling environment. Otherwise the global environment is used.
con | An output text connection.

Details

An input text connection is opened and the character vector is copied at time the connection object is created, and close destroys the copy.

An output text connection is opened and creates an R character vector of the given name in the user's workspace or in the calling environment, depending on the value of the local argument. This object will at all times hold the completed lines of output to the connection, and isIncomplete will indicate if there is an incomplete final line. Closing the connection will output the final line, complete or not. (A line is complete once it has been terminated by end-of-line, represented by "\n" in R.) The output character vector has locked bindings (see lockBinding) until close is called on the connection. The character vector can also be retrieved via textConnectionValue, which is the only way to do so if object = NULL.

Opening a text connection with mode = "a" will attempt to append to an existing character vector with the given name in the user's workspace or the calling environment. If none is found (even if an object exists of the right name but the wrong type) a new character vector will be created, with a warning.

You cannot seek on a text connection, and seek will always return zero as the position.

Value

For textConnection, a connection object of class "textConnection" which inherits from class "connection".
For textConnectionValue, a character vector.

Note

As output text connections keep the character vector up to date line-by-line, they are relatively expensive to use, and it is often better to use an anonymous file() connection to collect output.

On platforms where vsnprintf does not return the needed length of output (e.g., Windows) there is a 100,000 character limit on the length of line for output connections: longer lines will be truncated with a warning.

References

Chambers, J. M. (1998) Programming with Data. A Guide to the S Language. Springer.
[S has input text conections only.]

See Also

connections, showConnections, pushBack, capture.output.

Examples

zz <- textConnection(LETTERS)
readLines(zz, 2)
scan(zz, "", 4)
pushBack(c("aa", "bb"), zz)
scan(zz, "", 4)
close(zz)

zz <- textConnection("foo", "w")
writeLines(c("testit1", "testit2"), zz)
cat("testit3 ", file=zz)
isIncomplete(zz)
cat("testit4\n", file=zz)
isIncomplete(zz)
close(zz)
foo

## Not run:
# capture R output: use part of example from help(lm)
zz <- textConnection("foo", "w")
ctl <- c(4.17, 5.58, 5.18, 6.11, 4.5, 4.61, 5.17, 4.53, 5.33, 5.14)
trt <- c(4.81, 4.17, 4.41, 3.59, 5.87, 3.83, 6.03, 4.89, 4.32, 4.69)
group <- gl(2, 10, 20, labels = c("Ctl", "Trt"))
weight <- c(ctl, trt)
sink(zz)
anova(lm.D9 <- lm(weight ~ group))
cat("\nSummary of Residuals:\n\n")
summary(resid(lm.D9))
sink()
close(zz)
cat(foo, sep = "\n")
## End(Not run)


Tilde Operator

Description

Tilde is used to separate the left- and right-hand sides in model formula.

Usage

y ~ model

Arguments

y, model symbolic expressions.

References

Chambers, J. M. and Hastie, T. J. (1992) Statistical models. Chapter 2 of Statistical Models in S eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole.

See Also

formula


Convert an R Object to a Character String

Description

This is a helper function for format to produce a single character string describing an R object.

Usage

toString(x, ...)

## Default S3 method:
toString(x, width = NULL, ...)

Arguments

x | The object to be converted.
width | Suggestion for the maximum field width. Values of NULL or 0 indicate no maximum. The minimum value accepted is 6 and smaller values are taken as 6.
... | Optional arguments passed to or from methods.

Details

This is a generic function for which methods can be written: only the default method is described here. Most methods should honor the width argument to specify the maximum display width (as measured by nchar(type = "width") of the result.

The default method first converts x to character and then concatenates the elements separated by ", ". If width is supplied and is not NULL, the default method returns the first width - 4 characters of the result with .... appended, if the full result would use more than width characters.

Value

A character vector of length 1 is returned.

Author(s)

Robert Gentleman

See Also

format

Examples

x <- c("a", "b", "aaaaaaaaaaa")
toString(x)
toString(x, width=8)


Interactive Tracing and Debugging of Calls to a Function or Method

Description

A call to trace allows you to insert debugging code (e.g., a call to browser or recover) at chosen places in any function. A call to untrace cancels the tracing. Specified methods can be traced the same way, without tracing all calls to the function. Trace code can be any R expression. Tracing can be temporarily turned on or off globally by calling tracingState.

Usage

trace(what, tracer, exit, at, print, signature,
      where = topenv(parent.frame()), edit = FALSE)
untrace(what, signature = NULL, where = topenv(parent.frame()))

tracingState(on = NULL)

Arguments

what | The name (quoted or not) of a function to be traced or untraced. For untrace or for trace with more than one argument, more than one name can be given in the quoted form, and the same action will be applied to each one.
tracer | Either a function or an unevaluated expression. The function will be called or the expression will be evaluated either at the beginning of the call, or before those steps in the call specified by the argument at. See the details section.
exit | Either a function or an unevaluated expression. The function will be called or the expression will be evaluated on exiting the function. See the details section.
at | optional numeric vector. If supplied, tracer will be called just before the corresponding step in the body of the function. See the details section.
print | If TRUE (as per default), a descriptive line is printed before any trace expression is evaluated.
signature | If this argument is supplied, it should be a signature for a method for function what. In this case, the method, and not the function itself, is traced.
edit | For complicated tracing, such as tracing within a loop inside the function, you will need to insert the desired calls by editing the body of the function. If so, supply the edit argument either as TRUE, or as the name of the editor you want to use. Then trace() will call edit and use the version of the function after you edit it. See the details section for additional information.
where | where to look for the function to be traced; by default, the top-level environment of the call to trace. An important use of this argument is to trace a function when it is called from a package with a namespace. The current namespace mechanism imports the functions to be called (with the exception of functions in the base package). The functions being called are not the same objects seen from the top-level (in general, the imported packages may not even be attached). Therefore, you must ensure that the correct versions are being traced. The way to do this is to set argument where to a function in the namespace. The tracing computations will then start looking in the environment of that function (which will be the namespace of the corresponding package). (Yes, it's subtle, but the semantics here are central to how namespaces work in R.)
on | logical; a call to tracingState returns TRUE if tracing is globally turned on, FALSE otherwise. An argument of one or the other of those values sets the state. If the tracing state is FALSE, none of the trace actions will actually occur (used, for example, by debugging functions to shut off tracing during debugging).

Details

The trace function operates by constructing a revised version of the function (or of the method, if signature is supplied), and assigning the new object back where the original was found. If only the what argument is given, a line of trace printing is produced for each call to the function (back compatible with the earlier version of trace).

The object constructed by trace is from a class that extends "function" and which contains the original, untraced version. A call to untrace re-assigns this version.

If the argument tracer or exit is the name of a function, the tracing expression will be a call to that function, with no arguments. This is the easiest and most common case, with the functions browser and recover the likeliest candidates; the former browses in the frame of the function being traced, and the latter allows browsing in any of the currently active calls.

The tracer or exit argument can also be an unevaluated expression (such as returned by a call to quote or substitute). This expression itself is inserted in the traced function, so it will typically involve arguments or local objects in the traced function. An expression of this form is useful if you only want to interact when certain conditions apply (and in this case you probably want to supply print=FALSE in the call to trace also).

When the at argument is supplied, it should be a vector of integers referring to the substeps of the body of the function (this only works if the body of the function is enclosed in { ...}. In this case tracer is not called on entry, but instead just before evaluating each of the steps listed in at. (Hint: you don't want to try to count the steps in the printed version of a function; instead, look at as.list(body(f)) to get the numbers associated with the steps in function f.)

An intrinsic limitation in the exit argument is that it won't work if the function itself uses on.exit, since the existing calls will override the one supplied by trace.

Tracing does not nest. Any call to trace replaces previously traced versions of that function or method (except for edited versions as discussed below), and untrace always restores an untraced version. (Allowing nested tracing has too many potentials for confusion and for accidentally leaving traced versions behind.)

When the edit argument is used repeatedly with no call to untrace on the same function or method in between, the previously edited version is retained. If you want to throw away all the previous tracing and then edit, call untrace before the next call to trace. Editing may be combined with automatic tracing; just supply the other arguments such as tracer, and the edit argument as well. The edit=TRUE argument uses the default editor (see edit).

Tracing primitive functions (builtins and specials) from the base package works, but only by a special mechanism and not very informatively. Tracing a primitive causes the primitive to be replaced by a function with argument ... (only). You can get a bit of information out, but not much. A warning message is issued when trace is used on a primitive.

The practice of saving the traced version of the function back where the function came from means that tracing carries over from one session to another, if the traced function is saved in the session image. (In the next session, untrace will remove the tracing.) On the other hand, functions that were in a package, not in the global environment, are not saved in the image, so tracing expires with the session for such functions.

Tracing a method is basically just like tracing a function, with the exception that the traced version is stored by a call to setMethod rather than by direct assignment, and so is the untraced version after a call to untrace.

The version of trace described here is largely compatible with the version in S-Plus, although the two work by entirely different mechanisms. The S-Plus trace uses the session frame, with the result that tracing never carries over from one session to another (R does not have a session frame). Another relevant distinction has nothing directly to do with trace: The browser in S-Plus allows changes to be made to the frame being browsed, and the changes will persist after exiting the browser. The R browser allows changes, but they disappear when the browser exits. This may be relevant in that the S-Plus version allows you to experiment with code changes interactively, but the R version does not. (A future revision may include a “destructive” browser for R.)

Value

In the simple version (just the first argument), invisible NULL. Otherwise, the traced function(s) name(s). The relevant consequence is the assignment that takes place.

Note

The version of function tracing that includes any of the arguments except for the function name requires the methods package (because it uses special classes of objects to store and restore versions of the traced functions).

If methods dispatch is not currently on, trace will load the methods namespace, but will not put the methods package on the search list.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

browser and recover, the likeliest tracing functions; also, quote and substitute for constructing general expressions.

Examples

##  Very simple use
trace(sum)
hist(rnorm(100)) # shows about 3-4 calls to sum()
untrace(sum)

if(.isMethodsDispatchOn()) { # non-simple use needs 'methods' package

 f <- function(x, y) {
     y <- pmax(y, .001)
     x ^ y
 }

 ## arrange to call the browser on entering and exiting
 ## function f
 trace("f", browser, exit = browser)

 ## instead, conditionally assign some data, and then browse
 ## on exit, but only then.  Don't bother me otherwise

 trace("f", quote(if(any(y < 0)) yOrig <- y),
       exit = quote(if(exists("yOrig")) browser()),
       print = FALSE)

 ## trace a utility function, with recover so we
 ## can browse in the calling functions as well.

 trace("as.matrix", recover)

 ## turn off the tracing

 untrace(c("f", "as.matrix"))

 ## Not run:
 ## trace calls to the function lm() that come from the nlme package
 ## (The function nlme is in that package, and the package has a namespace,
 ## so the where= argument must be used to get the right version of lm)

 trace(lm, exit = recover, where = nlme)
 ## End(Not run)
}


Print Call Stacks

Description

By default traceback() prints the call stack of the last uncaught error, i.e., the sequence of calls that lead to the error. This is useful when an error occurs with an unidentifiable error message. It can also be used to print arbitrary lists of deparsed calls.

Usage

traceback(x = NULL, max.lines = getOption("deparse.max.lines"))

Arguments

x | NULL (default, meaning .Traceback), or a list or pairlist of deparsed calls.
max.lines | The maximum number of lines to be printed per call. The default is unlimited.

Details

The stack of the last uncaught error is stored as a list of deparsed calls in .Traceback, which traceback prints in a user-friendly format. The stack of deparsed calls always contains all function calls and all foreign function calls (such as .Call): if profiling is in progress it will include calls to some primitive functions. (Calls to builtins are included, but not to specials.)

Errors which are caught via try or tryCatch do not generate a traceback, so what is printed is the call sequence for the last uncaught error, and not necessarily for the last error.

Value

traceback() returns nothing, but prints the deparsed call stack deepest call first. The calls may print on more than one line, and the first line for each call is labelled by the frame number. The number of lines printed per call can be limited via max.lines.

Warning

It is undocumented where .Traceback is stored nor that it is visible, and this is subject to change. Prior to R 2.4.0 it was stored in the workspace, but no longer.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Examples

foo <- function(x) { print(1); bar(2) }
bar <- function(x) { x + a.variable.which.does.not.exist }
## Not run:
foo(2) # gives a strange error
traceback()
## End(Not run)
## 2: bar(2)
## 1: foo(2)
bar
## Ah, this is the culprit ...


Transform an Object, for Example a Data Frame

transform(base) R Documentation

Transform an Object for Example a Data Frame

Description

transform is a generic function, which—at least currently—only does anything useful with data frames. transform.default converts its first argument to a data frame if possible and calls transform.data.frame.

Usage

transform(`_data`, ...)

Arguments

_data | The object to be transformed
... | Further arguments of the form tag=value

Details

The ... arguments to transform.data.frame are tagged vector expressions, which are evaluated in the data frame _data. The tags are matched against names(_data), and for those that match, the value replace the corresponding variable in _data, and the others are appended to _data.

Value

The modified value of _data.

Note

Prior to R 2.3.0, the first argument was named x, but this caused trouble if people wanted to create a variable of that name. Names starting with an underscore are syntactically invalid, so the current choice should be less problematic.

If some of the values are not vectors of the appropriate length, you deserve whatever you get!

Author(s)

Peter Dalgaard

See Also

subset, list, data.frame

Examples

transform(airquality, Ozone = -Ozone)
transform(airquality, new = -Ozone, Temp = (Temp-32)/1.8)

attach(airquality)
transform(Ozone, logOzone = log(Ozone)) # marginally interesting ...
detach(airquality)


Trigonometric Functions

Description

These functions give the obvious trigonometric functions. They respectively compute the cosine, sine, tangent, arc-cosine, arc-sine, arc-tangent, and the two-argument arc-tangent.

Usage

cos(x)
sin(x)
tan(x)
acos(x)
asin(x)
atan(x)
atan2(y, x)

Arguments

x, y numeric or complex vectors.

Details

The arc-tangent of two arguments atan2(y, x) returns the angle between the x-axis and the vector from the origin to (x, y), i.e., for positive arguments atan2(y, x) == atan(y/x).

Angles are in radians, not degrees (i.e., a right angle is π/2).

All except atan2 are generic functions: methods can be defined for them individually or via the Math group generic.

Complex values

For the inverse trigonometric functions, branch cuts are defined as in Abramowitz and Stegun, figure 4.4, page 79. Continuity on the branch cuts is standard.

For asin() and acos(), there are two cuts, both along the real axis: (-Inf, -1] and [1, Inf). Functions asin() and acos() are continuous from above on the interval (-Inf, -1] and continuous from below on [1, Inf).

For atan() there are two cuts, both along the pure imaginary axis: (-1i*Inf, -1i] and [1i, 1i*Inf). It is continuous from the left on the interval (-1i*Inf, -1i] and from the right on the interval [1i, 1i*Inf).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Abramowitz, M. and Stegun, I. A. (1972). Handbook of Mathematical Functions, New York: Dover.
Chapter 4. Elementary Transcendental Functions: Logarithmic, Exponential, Circular and Hyperbolic Functions


Try an Expression Allowing Error Recovery

Description

try is a wrapper to run an expression that might fail and allow the user's code to handle error-recovery.

Usage

try(expr, silent = FALSE)

Arguments

expr | an R expression to try.
silent | logical: should the report of error messages be suppressed?

Details

try evaluates an expression and traps any errors that occur during the evaluation. try establishes a handler for errors that uses the default error handling protocol. It also establishes a tryRestart restart that can be used by invokeRestart.

Value

The value of the expression if expr is evaluated without error, but an invisible object of class "try-error" containing the error message if it fails. The normal error handling will print the same message unless options("show.error.messages") is false or the call includes silent = TRUE.

See Also

options for setting error handlers and suppressing the printing of error messages; geterrmessage for retrieving the last error message. tryCatch provides another means of catching and handling errors.

Examples

## this example will not work correctly in example(try), but
## it does work correctly if pasted in
options(show.error.messages = FALSE)
try(log("a"))
print(.Last.value)
options(show.error.messages = TRUE)

## alternatively,
print(try(log("a"), TRUE))

## run a simulation, keep only the results that worked.
set.seed(123)
x <- rnorm(50)
doit <- function(x)
{
    x <- sample(x, replace=TRUE)
    if(length(unique(x)) > 30) mean(x)
    else stop("too few unique points")
}
## alternative 1
res <- lapply(1:100, function(i) try(doit(x), TRUE))
## alternative 2
## Not run:
res <- vector("list", 100)
for(i in 1:100) res[[i]] <- try(doit(x), TRUE)
## End(Not run)
unlist(res[sapply(res, function(x) !inherits(x, "try-error"))])


Type Conversion on Character Variables

Description

Convert a character vector to logical, integer, numeric, complex or factor as appropriate.

Usage

type.convert(x, na.strings = "NA", as.is = FALSE, dec = ".")

Arguments

x | a character vector.
na.strings | a vector of strings which are to be interpreted as NA values. Blank fields are also considered to be missing values in logical, integer, numeric or complex vectors.
as.is | logical. See Details.
dec | the character to be assumed for decimal points.

Details

This is principally a helper function for read.table. Given a character vector, it attempts to convert it to logical, integer, numeric or complex, and failing that converts it to factor unless as.is = TRUE. The first type that can accept all the non-missing values is chosen.

Vectors which are entirely missing values are converted to logical, since NA is primarily logical.

Value

A vector of the selected class, or a factor.

See Also

read.table


The Type of an Object

Description

typeof determines the (R internal) type or storage mode of any object

Usage

typeof(x)

Arguments

x any R object.

Value

A character string. The possible values are listed in the structure TypeTable in ‘src/main/util.c’. Current values are the vector types "logical", "integer", "double", "complex", "character", "raw" and "list", "NULL", "closure" (function), "special" and "builtin" (basic functions and operators), "environment", and others that are unlikely to be seen at user level ("symbol", "pairlist", "promise", "language", "char", "...", "any", "expression", "externalptr", "bytecode" and "weakref").
As from R 2.4.0, "S4" can occur to refer to some objects with formal (S4) classes.

See Also

mode, storage.mode.

Examples

typeof(2)
mode(2)


Extract Unique Elements

Description

unique returns a vector, data frame or array like x but with duplicate elements removed.

Usage

unique(x, incomparables = FALSE, ...)

## S3 method for class 'matrix':
unique(x, incomparables = FALSE, MARGIN = 1, ...)

## S3 method for class 'array':
unique(x, incomparables = FALSE, MARGIN = 1, ...)

Arguments

x | a vector or a data frame or an array or NULL.
incomparables | a vector of values that cannot be compared. Currently, FALSE is the only possible value, meaning that all values can be compared.
... | arguments for particular methods.
MARGIN | the array margin to be held fixed: a single integer.

Details

This is a generic function with methods for vectors, data frames and arrays (including matrices).

The array method calculates for each element of the dimension specified by MARGIN if the remaining dimensions are identical to those for an earlier element (in row-major order). This would most commonly be used for matrices to find unique rows (the default) or columns (with MARGIN = 2).

Value

For a vector, an object of the same type of x, but with only one copy of each duplicated element. No attributes are copied (so the result has no names).
For a data frame, a data frame is returned with the same columns but possibly fewer rows (and with row names from the first occurrences of the unique rows).
A matrix or array is subsetted by [, drop = FALSE], so dimensions and dimnames are copied appropriately, and the result always has the same number of dimensions as x.

Warning

Using this for lists is potentially slow, especially if the elements are not atomic vectors (see vector) or differ only in their attributes. In the worst case it is O(n^2).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

duplicated which gives the indices of duplicated elements.

Examples

unique(c(3:5, 11:8, 8 + 0:5))
length(unique(sample(100, 100, replace=TRUE)))
## approximately 100(1 - 1/e) = 63.21

unique(iris)


Delete Files and Directories

Description

unlink deletes the file(s) or directories specified by x.

Usage

unlink(x, recursive = FALSE)

Arguments

x | a character vector with the names of the file(s) or directories to be deleted. Wildcards (normally ‘*’ and ‘?’) are allowed.
recursive | logical. Should directories be deleted recursively?

Details

If recursive = FALSE directories are not deleted, not even empty ones.

file.remove can only remove files, but gives more detailed error information.

Value

0 for success, 1 for failure. Not deleting a non-existent file is not a failure.

Note

Prior to R version 1.2.0 the default on Unix was recursive = TRUE, and on Windows empty directories could be deleted.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

file.remove.


Flatten Lists

Description

Given a list structure x, unlist simplifies it to produce a vector which contains all the atomic components which occur in x.

Usage

unlist(x, recursive = TRUE, use.names = TRUE)

Arguments

x | An R object, typically a list or vector.
recursive | logical. Should unlisting be applied to list components of x?
use.names | logical. Should names be preserved?

Details

unlist is generic: you can write methods to handle specific classes of objects, see InternalMethods.

If x has length zero the result is NULL.

If recursive = FALSE, the function will not recurse beyond the first level items in x.

Factors are treated specially. If all non-list elements of x are factors (or ordered factors) then the result will be a factor with levels the union of the level sets of the elements, in the order the levels occur in the level sets of the elements (which means that if all the elements have the same level set, that is the level set of the result).

x can be an atomic vector, but then unlist does nothing useful, not even drop names.

By default, unlist tries to retain the naming information present in x. If use.names = FALSE all naming information is dropped.

Where possible the list elements are coerced to a common mode during the unlisting, and so the result often ends up as a character vector. Vectors will be coerced to the highest type of the components in the hierarchy NULL < raw < logical < integer < real < complex < character < list < expression: pairlists are treated as lists.

A list is a (generic) vector, and the simplified vector might still be a list (and might be unchanged). Non-vector elements of the list (for example language elements such as names, formulas and calls) are not coerced, and so a list containing one or more of these remains a list. (The effect of unlisting an lm fit is a list which has individual residuals as components.)

Value

NULL or an expression or a vector of an appropriate mode to hold the list components.
The output type is determined from the highest type of the components in the hierarchy raw < logical < integer < real < complex < character < list < expression, after coercion of pairlists to lists.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

c, as.list.

Examples

unlist(options())
unlist(options(), use.names=FALSE)

l.ex <- list(a = list(1:5, LETTERS[1:5]), b = "Z", c = NA)
unlist(l.ex, recursive = FALSE)
unlist(l.ex, recursive = TRUE)

l1 <- list(a="a", b=2, c=pi+2i)
unlist(l1) # a character vector
l2 <- list(a="a", b=as.name("b"), c=pi+2i)
unlist(l2) # remains a list


Remove 'names' or 'dimnames'

Description

Remove the names or dimnames attribute of an R object.

Usage

unname(obj, force = FALSE)

Arguments

obj | the R object which is wanted “nameless”.
force | logical; if true, the dimnames are even removed from data.frames. This argument is currently experimental and hence might change!

Value

Object as obj but without names or dimnames.

Examples

## Answering a question on R-help (14 Oct 1999):
col3 <- 750+ 100* rt(1500, df = 3)
breaks <- factor(cut(col3,breaks=360+5*(0:155)))
z <- table(breaks)
z[1:5] # The names are larger than the data ...
barplot(unname(z), axes= FALSE)


Class Methods

Description

R possesses a simple generic function mechanism which can be used for an object-oriented style of programming. Method dispatch takes place based on the class(es) of the first argument to the generic function or of the object supplied as an argument to UseMethod or NextMethod.

Usage

UseMethod(generic, object)

NextMethod(generic = NULL, object = NULL, ...)

Arguments

generic | a character string naming a function (and not a built-in operator). Required for UseMethod.
object | for UseMethod: an object whose class will determine the method to be dispatched. Defaults to the first argument of the enclosing function.
... | further arguments to be passed to the next method.

Details

An R “object” is a data object which has a class attribute. A class attribute is a character vector giving the names of the classes which the object “inherits” from. If the object does not have a class attribute, it has an implicit class. Matrices and arrays have class "matrix" or"array" followed by the class of the underlying vector. Most vectors have class the result of mode(x), except that integer vectors have class c("integer", "numeric") and real vectors have class c("double", "numeric").

When a function calling UseMethod("fun") is applied to an object with class attribute c("first", "second"), the system searches for a function called fun.first and, if it finds it, applies it to the object. If no such function is found a function called fun.second is tried. If no class name produces a suitable function, the function fun.default is used, if it exists, or an error results.

Function methods can be used to find out about the methods for a particular generic function or class.

UseMethod is a primitive function so positional matching is used and names of supplied arguments are ignored. It is not the only means of dispatch of methods, for there are internal generic functions.

NextMethod invokes the next method (determined by the class vector, either of the object supplied to the generic, or of the first argument to the function containing NextMethod if a method was invoked directly). Normally NextMethod is used with only one argument, generic, but if further arguments are supplied these modify the call to the next method.

NextMethod should not be called except in methods called by UseMethod or from internal generics (see InternalGenerics). In particular it will not work inside anonymous calling functions (e.g. get("print.ts")(AirPassengers)).

Name spaces can register methods for generic functions. To support this, UseMethod and NextMethod search for methods in two places: first in the environment in which the generic function is called, and then in the registration data base for the environment in which the generic is defined (typically a name space). So methods for a generic function need to be available in the environment of the call to the generic, or they must be registered. (It does not matter whether they are visible in the environment in which the generic is defined.)

Technical Details

Now for some obscure details that need to appear somewhere. These comments will be slightly different than those in Chambers(1992). (See also the draft ‘R Language Definition’.) UseMethod creates a “new” function call with arguments matched as they came in to the generic. Any local variables defined before the call to UseMethod are retained (unlike S). Any statements after the call to UseMethod will not be evaluated as UseMethod does not return. UseMethod can be called with more than two arguments: a warning will be given and additional arguments ignored. (They are not completely ignored in S.) If it is called with just one argument, the class of the first argument of the enclosing function is used as object: unlike S this is the first actual argument passed and not the current value of the object of that name.

NextMethod works by creating a special call frame for the next method. If no new arguments are supplied, the arguments will be the same in number, order and name as those to the current method but their values will be promises to evaluate their name in the current method and environment. Any named arguments matched to ... are handled specially: they either replace existing arguments of the same name or are appended to the argument list. They are passed on as the promise that was supplied as an argument to the current environment. (S does this differently!) If they have been evaluated in the current (or a previous environment) they remain evaluated. (This is a complex area, and subject to change: see the draft ‘R Language Definition’.)

The search for methods for NextMethod is slightly different from that for UseMethod. Finding no fun.default is not necessarily an error, as the search continues to the generic itself. This is to pick up an internal generic like [ which has no separate default method, and succeeds only if the generic is a primitive function or a wrapper for a .Internal function of the same name. (When a primitive is called as the default method, argument matching may not work as described above due to the different semantics of primitives.)

You will see objects such as .Generic, .Method, and .Class used in methods. These are set in the environment within which the method is evaluated by the dispatch mechanism, which is as follows:

  1. Find the context for the calling function (the generic): this gives us the unevaluated arguments for the original call.
  2. Evaluate the object (usually an argument) to be used for dispatch, and find a method (possibly the default method) or throw an error.
  3. Create an environment for evaluating the method and insert special variables (see below) into that environment. Also copy any variables in the environment of the generic that are not formal (or actual) arguments.
  4. Fix up the argument list to be the arguments of the call matched to the formals of the method.

.Generic is a length-one character vector naming the generic function.

.Method is a character vector (normally of length one) naming the method function. (For functions in the group generic Ops it is of length two.)

.Class is a character vector of classes used to find the next method. NextMethod adds an attribute "previous" to .Class giving the .Class last used for dispatch, and shifts .Class along to that used for dispatch.

.GenericCallEnv and .GenericDefEnv are the environments of the call to be generic and defining the generic respectively. (The latter is used to find methods registered for the generic.)

Note that .Class is set when the generic is called, and is unchanged if the class of the dispatching argument is changed in a method. It is possible to change the method that NextMethod would dispatch by manipulating .Class, but ‘this is not recommended unless you understand the inheritance mechanism thoroughly’ (Chambers & Hastie, 1992, p. 469).

Historical note

Prior to R 2.1.0 UseMethod accepted a call with no arguments and tried to deduce the generic from the context. This was undocumented on the help page. It is allowed but ‘strongly discouraged’ in S-PLUS, and is no longer allowed in R.

Note

This scheme is called S3 (S version 3). For new projects, it is recommended to use the more flexible and robust S4 scheme provided in the methods package.

References

Chambers, J. M. (1992) Classes and methods: object-oriented programming in S. Appendix A of Statistical Models in S eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole.

See Also

The draft ‘R Language Definition’.

methods, class, getS3method.


Functions to Get and Set Hooks for Load, Attach, Detach and Unload

UserHooks(base) R Documentation

Functions to Get and Set Hooks for Load Attach Detach and Unload

Description

These functions allow users to set actions to be taken before packages are attached/detached and namespaces are (un)loaded.

Usage

getHook(hookName)
setHook(hookName, value, action = c("append", "prepend", "replace"))

packageEvent(pkgname,
             event = c("onLoad", "attach", "detach", "onUnload"))

Arguments

hookName | character string: the hook name
pkgname | character string: the package/namespace name. If versioned install has been used, pkgname should be the unversioned name of the package (but any version information will be stripped).
event | character string: an event for the package
value | A function, or for action="replace", NULL.
action | The action to be taken. The names can be appreviated.

Details

setHook provides a general mechanism for users to register hooks, a list of functions to be called from system (or user) functions. The initial set of hooks is associated with events on packages/namespaces: these hooks are named via calls to packageEvent.

To remove a hook completely, call setHook(hookName, NULL, "replace").

When an R package is attached by library, it can call initialization code via a function .First.lib, and when it is detach-ed it can tidy up via a function .Last.lib. Users can add their own initialization code via the hooks provided by these functions, functions which will be called as funname(pkgname, pkgpath) inside a try call. (The attach hook is called after .First.lib and the detach hook before .Last.lib.)

If a package has a namespace, there are two further actions, when the namespace is loaded (before being attached and after .onLoad is called ) and when it is unloaded (after being detached and before .onUnload). Note that code in these hooks is run without the package being on the search path, so objects in the package need to be referred to using the double colon operator as in the example. (Unlike .onLoad, the user hook is run after the name space has been sealed.)

Hooks are normally run in the order shown by getHook, but the "detach" and "onUnload" hooks are run in reverse order so the default for package events is to add hooks ‘inside’ existing ones.

Note that when an R session is finished, packages are not detached and namespaces are not unloaded, so the corresponding hooks will not be run.

The hooks are stored in the environment .userHooksEnv in the base package, with ‘mangled’ names.

Value

For getHook function, a list of functions (possible empty). For setHook function, no return value. For packageEvent, the derived hook name (a character string).

See Also

library, detach, loadNamespace.

Other hooks may be added later: plot.new and persp already have them.

Examples

setHook(packageEvent("grDevices", "onLoad"),
        function(...) grDevices::ps.options(horizontal=FALSE))


Convert to or from UTF-8-enconded Character Vectors

Description

Conversion of UTF-8 encoded character vectors to and from integer vectors.

Usage

utf8ToInt(x)
intToUtf8(x, multiple = FALSE)

Arguments

x | object to be converted.
multiple | logical: should the conversion be to a single character string or multiple individual characters?

Details

These will work in any locale, including on machines that do not otherwise support multi-byte character sets.

Value

utf8ToInt converts a length-one character string encoded in UTF-8 to an integer vector of (numeric) UTF-8 code points.
intToUtf8 converts a vector of (numeric) UTF-8 code points either to a single character string or a character vector of single characters. (Note that a single character string could contain embedded nuls.)


Vectors

Description

vector produces a vector of the given length and mode.

as.vector, a generic, attempts to coerce its argument into a vector of mode mode (the default is to coerce to whichever mode is most convenient).

is.vector returns TRUE if x is a vector (of mode logical, integer, real, complex, character, raw or list if not specified) or expression and FALSE otherwise.

Usage

vector(mode = "logical", length = 0)
as.vector(x, mode = "any")
is.vector(x, mode = "any")

Arguments

mode | A character string giving an atomic mode or "list", or (not for vector) "any".
length | A non-negative integer specifying the desired length.
x | An object.

Details

The atomic modes are "logical", "integer", "numeric", "complex", "character" and "raw".

is.vector returns FALSE if x has any attributes except names. (This is incompatible with S.) On the other hand, as.vector removes all attributes including names for results of atomic mode.

Note that factors are not vectors; is.vector returns FALSE and as.vector converts to a character vector for mode = "any".

Value

For vector, a vector of the given length and mode. Logical vector elements are initialized to FALSE, numeric vector elements to 0, character vector elements to "", raw vector elements to nul bytes and list elements to NULL.
All attributes are removed from the answer if it is of an atomic mode.

Note

as.vector and is.vector are quite distinct from the meaning of the formal class "vector" in the methods package, and hence as(x, "vector") and is(x, "vector").

modes of "symbol", "pairlist" and "expression" are allowed but have long been undocumented.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

c, is.numeric, is.list, etc.

Examples

df <- data.frame(x=1:3, y=5:7)
## Not run:
## Error:
  as.vector(data.frame(x=1:3, y=5:7), mode="numeric")
## End(Not run)

x <- c(a = 1, b = 2)
is.vector(x)
as.vector(x)
all.equal(x, as.vector(x)) ## FALSE

###-- All the following are TRUE:
is.list(df)
! is.vector(df)
! is.vector(df, mode="list")

is.vector(list(), mode="list")
is.vector(NULL,   mode="NULL")


Version Information

Description

R.Version() provides detailed information about the version of R running.

R.version is a variable (a list) holding this information (and version is a copy of it for S compatibility).

Usage

R.Version()
R.version
R.version.string
version

Value

R.Version returns a list with character-string components

platform | the platform for which R was built. A triplet of the form CPU-VENDOR-OS, as determined by the configure script. E.g, "i586-unknown-linux" or "i386-pc-mingw32".
arch | the architecture (CPU) R was built on/for.
os | the underlying operating system
system | CPU and OS, separated by a comma.
status | the status of the version (e.g., "Alpha")
major | the major version number
minor | the minor version number, including the patchlevel
year | the year the version was released
month | the month the version was released
day | the day the version was released
svn rev | the Subversion revision number, which should be either "unknown" or a single number. (A range of numbers or a number with M or S appended indicates inconsistencies in the sources used to build this version of R.)
language | always "R".
version.string | a character string concatenating some of the info above, useful for plotting, etc.

R.version and version are lists of class "simple.list" which has a print method.

Note

Do not use R.version$os to test the platform the code is running on: use .Platform$OS.type instead. Slightly different versions of the OS may report different values of R.version$os, as may different versions of R.

R.version.string is a copy of R.version$version.string for simplicity and backwards compatibility.

See Also

sessionInfo which provides additional information; getRversion, .Platform

Examples

R.version$os # to check how lucky you are ...
plot(0) # any plot
mtext(R.version.string, side=1,line=4,adj=1)# a useful bottom-right note


Warning Messages

Description

Generates a warning message that corresponds to its argument(s) and (optionally) the expression or function from which it was called.

Usage

warning(..., call. = TRUE, immediate. = FALSE, domain = NULL)
suppressWarnings(expr)

Arguments

... | character vectors (which are pasted together with no separator), a condition object, or NULL.
call. | logical, indicating if the call should become part of the warning message.
immediate. | logical, indicating if the call should be output immediately, even if getOption(warn) <= 0.
expr | expression to evaluate.
domain | see gettext. If NA, messages will not be translated.

Details

The result depends on the value of options("warn") and on handlers established in the executing code.

warning signals a warning condition by (effectively) calling signalCondition. If there are no handlers or if all handlers return, then the value of warn is used to determine the appropriate action. If warn is negative warnings are ignored; if it is zero they are stored and printed after the top–level function has completed; if it is one they are printed as they occur and if it is 2 (or larger) warnings are turned into errors. Calling warning(immediate. = TRUE) turns warn <= 0 into warn = 1 for this call only.

If warn is zero (the default), a read-only variable last.warning is created. It contains the warnings which can be printed via a call to warnings.

Warnings will be truncated to getOption("warning.length") characters, default 1000.

While the warning is being processed, a muffleWarning restart is available. If this restart is invoked with invokeRestart, then warning returns immediately.

An attempt is made to coerce other types of inputs to warning to character vectors.

suppressWarnings evaluates its expression in a context that ignores all warnings.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

stop for fatal errors, message for diagnostic messages, warnings, and options with argument warn=.

gettext for the mechanisms for the automated translation of messages.

Examples

testit <- function() warning("testit")
testit() ## shows call
testit <- function() warning("problem in testit", call. = FALSE)
testit() ## no call
suppressWarnings(warning("testit"))


Print Warning Messages

Description

warnings and its print method print the variable last.warning in a pleasing form.

Usage

warnings(...)

Arguments

... arguments to be passed to cat.

Details

See the decription of options("warn") for the circumstances under which there is a last.warning object and warnings() is used. In essence this is if options(warn = 0) and warning has been called at least once.

It is possible that last.warning refers to the last recorded warning and not to the last warning, for example if options(warn) has been changed or if a catastrophic error occurred.

Warning

It is undocumented where last.warning is stored nor that it is visible, and this is subject to change. Prior to R 2.4.0 it was stored in the workspace, but no longer.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

warning.

Examples

## NB this example is intended to be pasted in,
##    rather than run by example()
ow <- options("warn")
for(w in -1:1) {
   options(warn = w); cat("\n warn =",w,"\n")
   for(i in 1:3) { cat(i,"..\n"); m <- matrix(1:7, 3,4) }
}
warnings()
options(ow) # reset


Extract Parts of a POSIXt or Date Object

Description

Extract the weekday, month or quarter, or the Julian time (days since some origin). These are generic functions: the methods for the internal date-time classes are documented here.

Usage

weekdays(x, abbreviate)
## S3 method for class 'POSIXt':
weekdays(x, abbreviate = FALSE)
## S3 method for class 'Date':
weekdays(x, abbreviate = FALSE)

months(x, abbreviate)
## S3 method for class 'POSIXt':
months(x, abbreviate = FALSE)
## S3 method for class 'Date':
months(x, abbreviate = FALSE)

quarters(x, abbreviate)
## S3 method for class 'POSIXt':
quarters(x, ...)
## S3 method for class 'Date':
quarters(x, ...)

julian(x, ...)
## S3 method for class 'POSIXt':
julian(x, origin = as.POSIXct("1970-01-01", tz="GMT"), ...)
## S3 method for class 'Date':
julian(x, origin = as.Date("1970-01-01"), ...)

Arguments

x | an object inheriting from class "POSIXt" or "Date".
abbreviate | logical. Should the names be abbreviated?
origin | an length-one object inheriting from class "POSIXt" or "Date".
... | arguments for other methods.

Value

weekdays and months return a character vector of names in the locale in use.
quarters returns a character vector of "Q1" to "Q4".
julian returns the number of days (possibly fractional) since the origin, with the origin as a "origin" attribute.

Note

Other components such as the day of the month or the year are very easy to compute: just use as.POSIXlt and extract the relevant component.

See Also

DateTimeClasses, Date

Examples

weekdays(.leap.seconds)
months(.leap.seconds)
quarters(.leap.seconds)


Which indices are TRUE?

Description

Give the TRUE indices of a logical object, allowing for array indices.

Usage

which(x, arr.ind = FALSE)

Arguments

x | a logical vector or array. NAs are allowed and omitted (treated as if FALSE).
arr.ind | logical; should array indices be returned when x is an array?

Value

If arr.ind == FALSE (the default), an integer vector with length equal to sum(x), i.e., to the number of TRUEs in x; Basically, the result is (1:length(x))[x].
If arr.ind == TRUE and x is an array (has a dim attribute), the result is a matrix whose rows each are the indices of one element of x; see Examples below.

Author(s)

Werner Stahel and Peter Holzer holzer@stat.math.ethz.ch, for the array case.

See Also

Logic, which.min for the index of the minimum or maximum, and match for the first index of an element in a vector, i.e., for a scalar a, match(a,x) is equivalent to min(which(x == a)) but much more efficient.

Examples

which(LETTERS == "R")
which(ll <- c(TRUE,FALSE,TRUE,NA,FALSE,FALSE,TRUE))#> 1 3 7
names(ll) <- letters[seq(ll)]
which(ll)
which((1:12)%%2 == 0) # which are even?
which(1:10 > 3, arr.ind=TRUE)

( m <- matrix(1:12,3,4) )
which(m %% 3 == 0)
which(m %% 3 == 0, arr.ind=TRUE)
rownames(m) <- paste("Case",1:3, sep="_")
which(m %% 5 == 0, arr.ind=TRUE)

dim(m) <- c(2,2,3); m
which(m %% 3 == 0, arr.ind=FALSE)
which(m %% 3 == 0, arr.ind=TRUE)

vm <- c(m)
dim(vm) <- length(vm) #-- funny thing with  length(dim(...)) == 1
which(vm %% 3 == 0, arr.ind=TRUE)


Where is the Min() or Max() ?

Description

Determines the location, i.e., index of the (first) minimum or maximum of a numeric vector.

Usage

which.min(x)
which.max(x)

Arguments

x numeric vector, whose min or max is searched (NAs are allowed).

Value

an integer of length 1 or 0 (iff x has no non-NAs) , giving the index of the first minimum or maximum respectively of x.
If this extremum is unique (or empty), the result is the same (but more efficient) as which(x == min(x)) or which(x == max(x)) respectively.

Author(s)

Martin Maechler

See Also

which, max.col, max, etc.

which.is.max in package nnet differs in breaking ties at random (and having a “fuzz” in the definition of ties).

Examples

x <- c(1:4,0:5,11)
which.min(x)
which.max(x)

## it *does* work with NA's present:
presidents[1:30]
range(presidents, na.rm = TRUE)
which.min(presidents)# 28
which.max(presidents)# 2


Evaluate an Expression in a Data Environment

Description

Evaluate an R expression in an environment constructed from data.

Usage

with(data, expr, ...)

Arguments

data | data to use for constructing an environment. For the default method this may be an environment, a list, a data frame, or an integer as in sys.call.
expr | expression to evaluate.
... | arguments to be passed to future methods.

Details

with is a generic function that evaluates expr in a local environment constructed from data. The environment has the caller's environment as its parent. This is useful for simplifying calls to modeling functions.

Note that assignments within expr take place in the constructed environment and not in the user's workspace.

See Also

evalq, attach.

Examples

require(stats); require(graphics)
#examples from glm:
## Not run:
library(MASS)
with(anorexia, {
    anorex.1 <- glm(Postwt ~ Prewt + Treat + offset(Prewt),
                    family = gaussian)
    summary(anorex.1)
})
## End(Not run)

with(data.frame(u = c(5,10,15,20,30,40,60,80,100),
                lot1 = c(118,58,42,35,27,25,21,19,18),
                lot2 = c(69,35,26,21,18,16,13,12,12)),
    list(summary(glm(lot1 ~ log(u), family = Gamma)),
         summary(glm(lot2 ~ log(u), family = Gamma))))

# example from boxplot:
with(ToothGrowth, {
    boxplot(len ~ dose, boxwex = 0.25, at = 1:3 - 0.2,
            subset = (supp == "VC"), col = "yellow",
            main = "Guinea Pigs' Tooth Growth",
            xlab = "Vitamin C dose mg",
            ylab = "tooth length", ylim = c(0,35))
    boxplot(len ~ dose, add = TRUE, boxwex = 0.25, at = 1:3 + 0.2,
            subset = supp == "OJ", col = "orange")
    legend(2, 9, c("Ascorbic acid", "Orange juice"),
           fill = c("yellow", "orange"))
})

# alternate form that avoids subset argument:
with(subset(ToothGrowth, supp == "VC"),
     boxplot(len ~ dose, boxwex = 0.25, at = 1:3 - 0.2,
             col = "yellow", main = "Guinea Pigs' Tooth Growth",
             xlab = "Vitamin C dose mg",
             ylab = "tooth length", ylim = c(0,35)))
with(subset(ToothGrowth,  supp == "OJ"),
     boxplot(len ~ dose, add = TRUE, boxwex = 0.25, at = 1:3 + 0.2,
             col = "orange"))
legend(2, 9, c("Ascorbic acid", "Orange juice"),
       fill = c("yellow", "orange"))


Write Data to a File

Description

The data (usually a matrix) x are written to file file. If x is a two-dimensional matrix you need to transpose it to get the columns in file the same as those in the internal representation.

Usage

write(x, file = "data",
      ncolumns = if(is.character(x)) 1 else 5,
      append = FALSE, sep = " ")

Arguments

x | the data to be written out.
file | A connection, or a character string naming the file to write to. If "", print to the standard output connection.
ncolumns | the number of columns to write the data in.
append | if TRUE the data x are appended to the connection.
sep | a string used to separate columns. Using sep = "\t" gives tab delimited output; default is " ".

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

write is a wrapper for cat, which gives further details on the format used.

save for writing any R objects, write.table for data frames, and scan for reading data.

Examples

# create a 2 by 5 matrix
x <- matrix(1:10,ncol=5)

# the file data contains x, two rows, five cols
# 1 3 5 7 9 will form the first row
write(t(x))

# Writing to the "console" 'tab-delimited'
# two rows, five cols but the first row is 1 2 3 4 5
write(x, "", sep = "\t")
unlink("data") # tidy up


Data Output

Description

write.table prints its required argument x (after converting it to a data frame if it is not one nor a matrix) to a file or connection.

Usage

write.table(x, file = "", append = FALSE, quote = TRUE, sep = " ",
            eol = "\n", na = "NA", dec = ".", row.names = TRUE,
            col.names = TRUE, qmethod = c("escape", "double"))

write.csv(...)
write.csv2(...)

Arguments

x | the object to be written, preferably a matrix or data frame. If not, it is attempted to coerce x to a data frame.
file | either a character string naming a file or a connection. "" indicates output to the console.
append | logical. If TRUE, the output is appended to the file. If FALSE, any existing file of the name is destroyed.
quote | a logical value (TRUE or FALSE) or a numeric vector. If TRUE, any character or factor columns will be surrounded by double quotes. If a numeric vector, its elements are taken as the indices of columns to quote. In both cases, row and column names are quoted if they are written. If FALSE, nothing is quoted.
sep | the field separator string. Values within each row of x are separated by this string.
eol | the character(s) to print at the end of each line (row).
na | the string to use for missing values in the data.
dec | the string to use for decimal points in numeric or complex columns: must be a single character.
row.names | either a logical value indicating whether the row names of x are to be written along with x, or a character vector of row names to be written.
col.names | either a logical value indicating whether the column names of x are to be written along with x, or a character vector of column names to be written. See the section on ‘CSV files’ for the meaning of col.names = NA.
qmethod | a character string specifying how to deal with embedded double quote characters when quoting strings. Must be one of "escape" (default), in which case the quote character is escaped in C style by a backslash, or "double", in which case it is doubled. You can specify just the initial letter.
... | arguments to write.table: col.names, sep, dec and qmethod cannot be altered.

Details

If the table has no columns the rownames will be written only if row.names=TRUE, and vice versa.

Real and complex numbers are written to the maximal possible precision.

If a data frame has matrix-like columns these will be converted to multiple columns in the result (via as.matrix) and so a character col.names or a numeric quote should refer to the columns in the result, not the input. Such matrix-like columns are unquoted by default.

Any columns in a data frame which are lists or have a class (e.g. dates) will be converted by the appropriate as.character method: such columns are unquoted by default. On the other hand, any class information for a matrix is discarded and non-atomic (e.g. list) matrices are coerced to character.

Only columns which have been converted to character will be quoted if specified by quote.

The dec argument only applies to columns that are not subject to conversion to character because they have a class or are part of a matrix-like column (or matrix), in particular to columns protected by I(). Use options("OutDec") to control such conversions.

In almost all cases the conversion of numeric quantities is governed by the options in force, in particular by "digits" and "scipen" (see options). For finer control, use format to make a character matrix/data frame, and call write.table on that.

These functions check for a user interrupt every 1000 lines of output.

CSV files

By default there is no column name for a column of row names. If col.names = NA and row.names = TRUE a blank column name is added, which is the convention used for CSV files to be read by spreadsheets.

write.csv and write.csv2 provide convenience wrappers for writing CSV files. They set sep, dec and qmethod, and col.names to NA if row.names = TRUE and TRUE otherwise.

write.csv uses "." for the decimal point and a comma for the separator.

write.csv2 uses a comma for the decimal point and a semicolon for the separator, the Excel convention for CSV files in some Western European locales.

These wrappers are deliberately inflexible: they are designed to ensure that the correct conventions are used to write a valid file. Attempts to change col.names, sep, dec or qmethod are ignored, with a warning.

Note

write.table can be slow for data frames with large numbers (hundreds or more) of columns: this is inevitable as each column could be of a different class and so must be handled separately. If they are all of the same class, consider using a matrix instead.

See Also

The ‘R Data Import/Export’ manual.

read.table, write.

write.matrix in package MASS.

Examples

## Not run:
## To write a CSV file for input to Excel one might use
x <- data.frame(a = I("a \" quote"), b = pi)
write.table(x, file = "foo.csv", sep = ",", col.names = NA,
            qmethod = "double")
## and to read this file back into R one needs
read.table("foo.csv", header = TRUE, sep = ",", row.names = 1)
## NB: you do need to specify a separator if qmethod = "double".

### Alternatively
write.csv(x, file = "foo.csv")
read.csv("foo.csv", row.names = 1)
## or without row names
write.csv(x, file = "foo.csv", row.names = FALSE)
read.csv("foo.csv")
## End(Not run)


Write Lines to a Connection

Description

Write text lines to a connection.

Usage

writeLines(text, con = stdout(), sep = "\n")

Arguments

text | A character vector
con | A connection object or a character string.
sep | character. A string to be written to the connection after each line of text.

Details

If the con is a character string, the function calls file to obtain a file connection which is opened for the duration of the function call.

If the connection is open it is written from its current position. If it is not open, it is opened for the duration of the call and then closed again.

Normally writeLines is used with a text connection, and the default separator is converted to the normal separator for that platform (LF on Unix/Linux, CRLF on Windows, CR on Classic MacOS). For more control, open a binary connection and specify the precise value you want written to the file in sep. For even more control, use writeChar on a binary connection.

See Also

connections, writeChar, writeBin, readLines, cat


Extract File from a Zip Archive

Description

This will extract the file named file from the zip archive, if possible, and write it in a temporary location.

Usage

zip.file.extract(file, zipname = "R.zip")

Arguments

file | A file name.
zipname | The file name of a zip archive, including the ".zip" extension if required.

Details

The method used is selected by options(unzip=). All platforms support an "internal" unzip: this is the default under Windows and the fall-back under Unix if no unzip program was found during configuration and R_UNZIPCMD is not set.

The file will be extracted if it is in the archive and any required unzip utility is available. It will probably be extracted to the directory given by tempdir, overwriting an existing file of that name.

Value

The name of the original or extracted file. Success is indicated by returning a different name.

Note

The "internal" method is very simple, and will not set file dates.


Numerical Characteristics of the Machine

Description

.Machine is a variable holding information on the numerical characteristics of the machine R is running on, such as the largest double or integer and the machine's precision.

Usage

.Machine

Details

The algorithm is based on Cody's (1988) subroutine MACHAR.

Note that on most platforms smaller positive values than .Machine$double.xmin can occur. On a typical R platform the smallest positive double is about 5e-324.

Value

A list with components (for simplicity, the prefix “double” is omitted in the explanations)

double.eps | the smallest positive floating-point number x such that 1 + x != 1. It equals base^ulp.digits if either base is 2 or rounding is 0; otherwise, it is (base^ulp.digits) / 2.
double.neg.eps | a small positive floating-point number x such that 1 - x != 1. It equals base^neg.ulp.digits if base is 2 or round is 0; otherwise, it is (base^neg.ulp.digits) / 2. As neg.ulp.digits is bounded below by -(digits + 3), neg.eps may not be the smallest number that can alter 1 by subtraction.
double.xmin | the smallest non-vanishing normalized floating-point power of the radix, i.e., base^min.exp.
double.xmax | the largest finite floating-point number. Typically, it is equal to (1 - neg.eps) * base^max.exp, but on some machines it is only the second, or perhaps third, largest number, being too small by 1 or 2 units in the last digit of the significand.
double.base | the radix for the floating-point representation
double.digits | the number of base digits in the floating-point significand
double.rounding the rounding action.
0 if floating-point addition chops;
1 if floating-point addition rounds, but not in the IEEE style;
2 if floating-point addition rounds in the IEEE style;
3 if floating-point addition chops, and there is partial underflow;
4 if floating-point addition rounds, but not in the IEEE style, and there is partial underflow;
5 if floating-point addition rounds in the IEEE style, and there is partial underflow
double.guard | the number of guard digits for multiplication with truncating arithmetic. It is 1 if floating-point arithmetic truncates and more than digits base base digits participate in the post-normalization shift of the floating-point significand in multiplication, and 0 otherwise.
double.ulp.digits | the largest negative integer i such that 1 + base^i != 1, except that it is bounded below by -(digits + 3).
double.neg.ulp.digits | the largest negative integer i such that 1 - base^i != 1, except that it is bounded below by -(digits + 3).
double.exponent | the number of bits (decimal places if base is 10) reserved for the representation of the exponent (including the bias or sign) of a floating-point number
double.min.exp | the largest in magnitude negative integer i such that base ^ i is positive and normalized.
double.max.exp | the smallest positive power of base that overflows.
integer.max | the largest integer which can be represented.
sizeof.long | the number of bytes in a C long type.
sizeof.longlong | the number of bytes in a C long long type. Will be zero if there is no such type.
sizeof.longdouble | the number of bytes in a C long double type. Will be zero if there is no such type.
sizeof.pointer | the number of bytes in a C SEXP type.

References

Cody, W. J. (1988) MACHAR: A subroutine to dynamically determine machine parameters. Transactions on Mathematical Software, 14, 4, 303–311.

See Also

.Platform for details of the platform.

Examples

.Machine
## or for a neat printout
noquote(unlist(format(.Machine)))


Internal Generic Functions

Description

Many R-internal functions are generic and allow methods to be written for.

Details

The following primitive and internal functions are generic, i.e., you can write methods for them:

[, [[, $, [<-, [[<-, $<-,

length, length<-,

dimnames<-, dimnames, dim<-, dim,

c, unlist,

as.character, as.vector, is.array, is.atomic, is.call, is.character, is.complex, is.double, is.environment, is.function, is.integer, is.language, is.logical, is.list, is.matrix, is.na, is.nan, is.null, is.numeric, is.object, is.pairlist, is.recursive, is.single, is.symbol, rep and seq.int.

Note that most of the group generic functions are also internal/primitive and allow methods to be written for them.

See Also

methods for the methods of non-Internal generic functions.


Listing of Packages

Description

.packages returns information about package availability.

Usage

.packages(all.available = FALSE, lib.loc = NULL)

Arguments

all.available | logical; if TRUE return a character vector of all available packages in lib.loc.
lib.loc | a character vector describing the location of R library trees to search through, or NULL. The default value of NULL corresponds to all libraries currently known.

Details

.packages() returns the “base names” of the currently attached packages invisibly whereas .packages(all.available = TRUE) gives (visibly) all packages available in the library location path lib.loc. For a package to be regarded as being available it must have a ‘DESCRIPTION’ file containing a valid version field.

Value

A character vector of package “base names”, invisible unless all.available = TRUE.

Author(s)

R core; Guido Masarotto for the all.available=TRUE part of .packages.

See Also

library, .libPaths.

Examples

(.packages())               # maybe just "base"
.packages(all = TRUE)       # return all available as character vector
require(splines)            # the same
(.packages())               # "splines", too
detach("package:splines")


Scripting Language Interface

Description

Run a script through its interpreter with given arguments.

Usage

.Script(interpreter, script, args, ...)

Arguments

interpreter | a character string naming the interpreter for the script.
script | a character string with the base file name of the script, which must be located in the ‘interpreter’ subdirectory of ‘R_HOME/share’.
args | a character string giving the arguments to pass to the script.
... | further arguments to be passed to system when invoking the interpreter on the script.

Note

This function is for R internal use only.

Examples

## not useful on Windows, where the help is zipped.
.Script("perl", "massage-Examples.pl",
        paste("tools", system.file("R-ex", package = "tools")))


Miscellaneous Internal/Programming Utilities

Description

Miscellaneous internal/programming utilities.

Usage

.standard_regexps()

Details

.standard_regexps returns a list of “standard” regexps, including elements named valid_package_name and valid_package_version with the obvious meanings. The regexps are not anchored.