The R Utils Package

The R Utils Package [R logo]

Help pages for package `utils' version 2.4.1

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

-- --

utils-package The R Utils Package

-- --

.helpForCall | Documentation
.tryHelp | Documentation
? | Documentation

-- A --

alarm | Alert the user
apropos | Find Objects by (Partial) Name
argsAnywhere | Retrieve an R Object, Including from a Namespace
as.character.person | Person Names and Contact Information
as.character.personList | Person Names and Contact Information
as.person | Person Names and Contact Information
as.personList | Person Names and Contact Information
assignInNamespace | Utility functions for Developing Namespaces
available.packages | Download Packages from CRAN-like repositories

-- B --

BATCH | Batch Execution of R
browseEnv | Browse Objects in Environment
browseURL | Load URL into a WWW Browser
bug.report | Send a Bug Report
build | Utilities for Building and Checking Add-on Packages

-- C --

capture.output | Send output to a character string or file
check | Utilities for Building and Checking Add-on Packages
checkCRAN | Managing Repository Mirrors
choose.dir | Choose a List of Files Interactively
choose.files | Choose a List of Files Interactively
chooseCRANmirror | Select a CRAN Mirror
CITATION | Writing Package CITATION Files
citation | Citing R and R Packages in Publications
citEntry | Writing Package CITATION Files
citFooter | Writing Package CITATION Files
citHeader | Writing Package CITATION Files
clipboard | Read/Write to/from the Windows Clipboard
close.socket | Close a Socket
combn | Generate All Combinations of n Elements, Taken m at a Time
compareVersion | Compare Two Package Version Numbers
contrib.url | Download Packages from CRAN-like repositories
CRAN.packages | Deprecated Functions in Package utils

-- D --

data | Data Sets
data.entry | Spreadsheet Interface for Entering Data
dataentry | Spreadsheet Interface for Entering Data
de | Spreadsheet Interface for Entering Data
debugger | Post-Mortem Debugging
demo | Demonstrations of R Functionality
DLL.version | DLL Version Information
download.file | Download File from the Internet
download.packages | Download Packages from CRAN-like repositories
dump.frames | Post-Mortem Debugging

-- E --

edit | Invoke a Text Editor
edit.data.frame | Edit Data Frames and Matrices
edit.default | Invoke a Text Editor
edit.matrix | Edit Data Frames and Matrices
edit.vignette | View or List Vignettes
emacs | Invoke a Text Editor
example | Run an Examples Section from the Online Help

-- F --

file.edit | Edit One or More Files
Filters | Choose a List of Files Interactively
find | Find Objects by (Partial) Name
fix | Fix an Object
fixInNamespace | Utility functions for Developing Namespaces
fixup.libraries.URLs | Update HTML documentation files
fixup.package.URLs | Update HTML documentation files
flush.console | Flush Output to A Console

-- G --

getAnywhere | Retrieve an R Object, Including from a Namespace
getClipboardFormats | Read/Write to/from the Windows Clipboard
getFromNamespace | Utility functions for Developing Namespaces
getIdentification | Set or get the Window Title
getS3method | Get An S3 Method
getWindowsHandle | Get a Windows Handle
getWindowTitle | Set or get the Window Title
glob2rx | Change Wildcard or Globbing Pattern into Regular Expression

-- H --

head | Return the First or Last Part of an Object
help | Documentation
help.search | Search the Help System
help.start | Hypertext Documentation
history | Load or Save or Display the Commands History

-- I --

index.search | Search Indices for Help Files
INSTALL | Install Add-on Packages from Sources
install.packages | Download Packages from CRAN-like repositories
installed.packages | Find Installed Packages

-- L --

limitedLabels | Browsing after an Error
link.html.help | Update HTML documentation files
loadhistory | Load or Save or Display the Commands History
loadRconsole | R for Windows Configuration
localeToCharset | Select a Suitable Encoding Name from a Locale Name
ls.str | List Objects and their Structure
lsf.str | List Objects and their Structure

-- M --

make.packages.html | Update HTML documentation files
make.search.html | Update HTML documentation files
make.socket | Create a Socket Connection
memory.limit | Report on Memory Allocation
memory.size | Report on Memory Allocation
menu | Menu Interaction Function
methods | List Methods for S3 Generic Functions or Classes
mirror2html | Managing Repository Mirrors
mirrorAdmin | Managing Repository Mirrors
modifyList | Recursively Modify Elements of a List

-- N --

new.packages | Download Packages from CRAN-like repositories
normalizePath | Express File Paths in Canonical Form

-- O --

object.size | Report the Space Allocated for an Object
old.packages | Download Packages from CRAN-like repositories

-- P --

package.skeleton | Create a Skeleton for a New Source Package
packageDescription | Package Description
packageStatus | Package Management Tools
page | Invoke a Pager on an R Object
person | Person Names and Contact Information
personList | Person Names and Contact Information
pico | Invoke a Text Editor
print.Bibtex | Converting R Objects to BibTeX or LaTeX
print.getAnywhere | Retrieve an R Object, Including from a Namespace
print.hsearch | Search the Help System
print.Latex | Converting R Objects to BibTeX or LaTeX
print.ls_str | List Objects and their Structure
print.MethodsFunction | List Methods for S3 Generic Functions or Classes
print.packageDescription | Package Description
print.packageIQR | Data Sets
print.packageStatus | Package Management Tools
print.sessionInfo | Collect Information About the Current R Session
print.socket | Create a Socket Connection
print.vignette | View or List Vignettes
prompt | Produce Prototype of an R Documentation File
promptData | Generate a Shell for Documentation of Data Sets
promptPackage | Generate a Shell for Documentation of a Package

-- R --

Rconsole | R for Windows Configuration
Rdevga | R for Windows Configuration
read.DIF | Data Input from Spreadsheet
read.fortran | Read fixed-format data
read.fwf | Read Fixed Width Format Files
read.socket | Read from or Write to a Socket
readCitationFile | Writing Package CITATION Files
readClipboard | Read/Write to/from the Windows Clipboard
readNEWS | Read R's NEWS file or a Similar One
recover | Browsing after an Error
REMOVE | Remove Add-on Packages
remove.packages | Remove Installed Packages
retracemem | Trace copying of objects
Rprof | Enable Profiling of R's Execution
Rprofmem | Enable Profiling of R's Memory Use
RSiteSearch | Search for Key Words or Phrases in the R-help Mailing List Archives or Documentation
Rtangle | R Driver for Stangle
RtangleSetup | R Driver for Stangle
RweaveLatex | R/LaTeX Driver for Sweave
RweaveLatexSetup | R/LaTeX Driver for Sweave

-- S --

savehistory | Load or Save or Display the Commands History
select.list | Select Items from a List
sessionInfo | Collect Information About the Current R Session
setRepositories | Select Package Repositories
setWindowTitle | Set or get the Window Title
SHLIB | Build a DLL for Dynamic Loading
shortPathName | Express File Paths in Short Form
Stangle | Automatic Generation of Reports
str | Compactly Display the Structure of an Arbitrary R Object
strOptions | Compactly Display the Structure of an Arbitrary R Object
summary.packageStatus | Package Management Tools
summaryRprof | Summarise Output of R Sampling Profiler
Sweave | Automatic Generation of Reports
SweaveSyntaxLatex | Automatic Generation of Reports
SweaveSyntaxNoweb | Automatic Generation of Reports
SweaveSyntConv | Convert Sweave Syntax

-- T --

tail | Return the First or Last Part of an Object
timestamp | Load or Save or Display the Commands History
toBibtex | Converting R Objects to BibTeX or LaTeX
toBibtex.citation | Citing R and R Packages in Publications
toBibtex.citationList | Citing R and R Packages in Publications
toBibtex.person | Person Names and Contact Information
toBibtex.personList | Person Names and Contact Information
toLatex | Converting R Objects to BibTeX or LaTeX
toLatex.sessionInfo | Collect Information About the Current R Session
topicName | Documentation
tracemem | Trace copying of objects

-- U --

untracemem | Trace copying of objects
update.packages | Download Packages from CRAN-like repositories
update.packageStatus | Package Management Tools
upgrade | Package Management Tools
url.show | Display a text URL
URLdecode | Encode or Decode a (partial) URL
URLencode | Encode or Decode a (partial) URL
utils | The R Utils Package
utils-deprecated | Deprecated Functions in Package utils

-- V --

vi | Invoke a Text Editor
vignette | View or List Vignettes

-- W --

win.version | Auxiliary Functions for the Windows Port
winDialog | Dialog Boxes under Windows
winDialogString | Dialog Boxes under Windows
winMenuAdd | User Menus under Windows
winMenuAddItem | User Menus under Windows
winMenuDel | User Menus under Windows
winMenuDelItem | User Menus under Windows
winMenuItems | User Menus under Windows
winMenuNames | User Menus under Windows
write.socket | Read from or Write to a Socket
writeClipboard | Read/Write to/from the Windows Clipboard
wsbrowser | Browse Objects in Environment

-- X --

xedit | Invoke a Text Editor
xemacs | Invoke a Text Editor

-- Z --

zip.unpack Auxiliary Functions for the Windows Port

-- misc --

[.getAnywhere Retrieve an R Object, Including from a Namespace


Alert the user

Description

Gives an audible or visual signal to the user.

Usage

alarm()

Details

alarm() works by sending a "\a" character to the console. On most platforms this will ring a bell, beep, or give some other signal to the user (unless standard output has been redirected).

Value

No useful value is returned.

Examples

alarm()
[Package utils version 2.4.1 Index]


Find Objects by (Partial) Name

Description

apropos returns a character vector giving the names of all objects in the search list matching what.

find is a different user interface to the same task as apropos.

Usage

apropos(what, where = FALSE, mode = "any")

find(what, mode = "any", numeric. = FALSE, simple.words = TRUE)

Arguments

what | name of an object, or regular expression to match against
where, numeric. | a logical indicating whether positions in the search list should also be returned
mode | character; if not "any", only objects whose mode equals mode are searched.
simple.words | logical; if TRUE, the what argument is only searched as whole word.

Details

If mode != "any" only those objects which are of mode mode are considered. If where is TRUE, the positions in the search list are returned as the names attribute.

find is a different user interface for the same task as apropos. However, by default (simple.words == TRUE), only full words are searched with grep(fixed = TRUE).

Author(s)

Kurt Hornik and Martin Maechler (May 1997).

See Also

glob2rx to convert wildcard patterns to regular expressions.

objects for listing objects from one place, help.search for searching the help system, search for the search path.

Examples

## Not run: apropos("lm")
apropos(ls)
apropos("lq")

cor <- 1:pi
find(cor)        #> ".GlobalEnv"   "package:stats"
find(cor, num=TRUE) # numbers with these names
find(cor, num=TRUE, mode="function")# only the second one
rm(cor)

## Not run: apropos(".", mode="list") # a long list

# need a DOUBLE backslash '\\' (in case you don't see it anymore)
apropos("\\[")

## Not run: # everything
length(apropos("."))

# those starting with 'pr'
apropos("^pr")

# the 1-letter things
apropos("^.$")
# the 1-2-letter things
apropos("^..?$")
# the 2-to-4 letter things
apropos("^.{2,4}$")

# the 8-and-more letter things
apropos("^.{8,}$")
table(nchar(apropos("^.{8,}$")))
## End(Not run)


Batch Execution of R

Description

Run R non-interactively with input from infile and send output (stdout/stderr) to another file.

Usage

R CMD BATCH [options] infile [outfile]

Arguments

infile | the name of a file with R code to be executed.
options | a list of R command line options, e.g., for setting the amount of memory available and controlling the load/save process. If infile starts with a -, use -- as the final option. The default options are --restore --save.
outfile | the name of a file to which to write output. If not given, the name used is that of infile, with a possible ‘.R’ extension stripped, and ‘.Rout’ appended.

Details

Use R CMD BATCH --help to be reminded of the usage.

By default, the input commands are printed along with the output. To suppress this behavior, add options(echo = FALSE) at the beginning of infile.

Files with an incomplete last line (no end of line mark) are now accepted.

Additional options can be set by the environment variable R_BATCH_OPTIONS: these come after --restore --save and before any options given on the command line.


Browse Objects in Environment

Description

The browseEnv function opens a browser with list of objects currently in sys.frame() environment.

Usage

browseEnv(envir = .GlobalEnv, pattern,
          excludepatt = "^last\.warning",
          html = .Platform$OS.type != "mac",
          expanded = TRUE, properties = NULL,
          main = NULL, debugMe = FALSE)

Arguments

envir | an environment the objects of which are to be browsed.
pattern | a regular expression for object subselection is passed to the internal ls() call.
excludepatt | a regular expression for dropping objects with matching names.
html | is used on non Macintosh machines to display the workspace on a HTML page in your favorite browser.
expanded | whether to show one level of recursion. It can be useful to switch it to FALSE if your workspace is large. This option is ignored if html is set to FALSE.
properties | a named list of global properties (of the objects chosen) to be showed in the browser; when NULL (as per default), user, date, and machine information is used.
main | a title string to be used in the browser; when NULL (as per default) a title is constructed.
debugMe | logical switch; if true, some diagnostic output is produced.

Details

Very experimental code. Only allows one level of recursion into object structures. The HTML version is not dynamic.

It can be generalized. See sources (‘..../library/base/R/databrowser.R’) for details.

wsbrowser() is currently just an internally used function; its argument list will certainly change.

Most probably, this should rather work through using the ‘tkWidget’ package (from www.Bioconductor.org).

See Also

str, ls.

Examples

if(interactive()) {
   ## create some interesting objects :
   ofa <- ordered(4:1)
   ex1 <- expression(1+ 0:9)
   ex3 <- expression(u,v, 1+ 0:9)
   example(factor, echo = FALSE)
   example(table, echo = FALSE)
   example(ftable, echo = FALSE)
   example(lm, echo = FALSE)
   example(str, echo = FALSE)

   ## and browse them:
   browseEnv()

   ## a (simple) function's environment:
   af12 <- approxfun(1:2, 1:2, method = "const")
   browseEnv(envir = environment(af12))
 }


Load URL into a WWW Browser

Description

Load a given URL into a WWW browser.

Usage

browseURL(url, browser = getOption("browser"))

Arguments

url | a non-empty character string giving the URL to be loaded.
browser | a non-empty character string giving the name of the program to be used as hypertext browser. It should be in the PATH, or a full path specified. Under Windows NULL is also allowed (and is the default), and implies that the file association mechanism will be used.

Examples

## Not run:
browseURL("http://www.r-project.org")
browseURL("file://c|/R/R-2.4.0/doc/html/index.html",
          browser="C:/Program Files/Mozilla Firefox/firefox.exe")
## End(Not run)


Send a Bug Report

Description

Invokes an editor to write a bug report and optionally mail it to the automated r-bugs repository at r-bugs@r-project.org. Some standard information on the current version and configuration of R are included automatically.

Usage

bug.report(subject = "",
           ccaddress = Sys.getenv("USER"),
           method = getOption("mailer"),
           address = "r-bugs@r-project.org",
           file = "R.bug.report")

Arguments

subject | Subject of the email. Please do not use single quotes (') in the subject! File separate bug reports for multiple bugs
ccaddress | Optional email address for copies (default is current user). Use ccaddress = FALSE for no copies.
method | Submission method, one of "mailx", "gnudoit", "none", or "ess".
address | Recipient's email address.
file | File to use for setting up the email (or storing it when method is "none" or sending mail fails).

Details

Currently direct submission of bug reports works only on Unix systems. If the submission method is "mailx", then the default editor is used to write the bug report. Which editor is used can be controlled using options, type getOption("editor") to see what editor is currently defined. Please use the help pages of the respective editor for details of usage. After saving the bug report (in the temporary file opened) and exiting the editor the report is mailed using a Unix command line mail utility such as mailx. A copy of the mail is sent to the current user.

If method is "gnudoit", then an emacs mail buffer is opened and used for sending the email.

If method is "none" or NULL (and in every case on Windows systems), then only an editor is opened to help writing the bug report. The report can then be copied to your favorite email program and be sent to the r-bugs list.

If method is "ess" the body of the mail is simply sent to stdout.

Value

Nothing useful.

When is there a bug?

If R executes an illegal instruction, or dies with an operating system error message that indicates a problem in the program (as opposed to something like “disk full”), then it is certainly a bug.

Taking forever to complete a command can be a bug, but you must make certain that it was really R's fault. Some commands simply take a long time. If the input was such that you KNOW it should have been processed quickly, report a bug. If you don't know whether the command should take a long time, find out by looking in the manual or by asking for assistance.

If a command you are familiar with causes an R error message in a case where its usual definition ought to be reasonable, it is probably a bug. If a command does the wrong thing, that is a bug. But be sure you know for certain what it ought to have done. If you aren't familiar with the command, or don't know for certain how the command is supposed to work, then it might actually be working right. Rather than jumping to conclusions, show the problem to someone who knows for certain.

Finally, a command's intended definition may not be best for statistical analysis. This is a very important sort of problem, but it is also a matter of judgment. Also, it is easy to come to such a conclusion out of ignorance of some of the existing features. It is probably best not to complain about such a problem until you have checked the documentation in the usual ways, feel confident that you understand it, and know for certain that what you want is not available. The mailing list r-devel@r-project.org is a better place for discussions of this sort than the bug list.

If you are not sure what the command is supposed to do after a careful reading of the manual this indicates a bug in the manual. The manual's job is to make everything clear. It is just as important to report documentation bugs as program bugs.

If the online argument list of a function disagrees with the manual, one of them must be wrong, so report the bug.

How to report a bug

When you decide that there is a bug, it is important to report it and to report it in a way which is useful. What is most useful is an exact description of what commands you type, from when you start R until the problem happens. Always include the version of R, machine, and operating system that you are using; type version in R to print this. To help us keep track of which bugs have been fixed and which are still open please send a separate report for each bug.

The most important principle in reporting a bug is to report FACTS, not hypotheses or categorizations. It is always easier to report the facts, but people seem to prefer to strain to posit explanations and report them instead. If the explanations are based on guesses about how R is implemented, they will be useless; we will have to try to figure out what the facts must have been to lead to such speculations. Sometimes this is impossible. But in any case, it is unnecessary work for us.

For example, suppose that on a data set which you know to be quite large the command data.frame(x, y, z, monday, tuesday) never returns. Do not report that data.frame() fails for large data sets. Perhaps it fails when a variable name is a day of the week. If this is so then when we got your report we would try out the data.frame() command on a large data set, probably with no day of the week variable name, and not see any problem. There is no way in the world that we could guess that we should try a day of the week variable name.

Or perhaps the command fails because the last command you used was a [ method that had a bug causing R's internal data structures to be corrupted and making the data.frame() command fail from then on. This is why we need to know what other commands you have typed (or read from your startup file).

It is very useful to try and find simple examples that produce apparently the same bug, and somewhat useful to find simple examples that might be expected to produce the bug but actually do not. If you want to debug the problem and find exactly what caused it, that is wonderful. You should still report the facts as well as any explanations or solutions.

Invoking R with the --vanilla option may help in isolating a bug. This ensures that the site profile and saved data files are not read.

A bug report can be generated using the bug.report() function. This automatically includes the version information and sends the bug to the correct address. Alternatively the bug report can be emailed to r-bugs@r-project.org or submitted to the Web page at http://bugs.r-project.org.

Bug reports on contributed packages should be sent to the package maintainer rather than to r-bugs.

Author(s)

This help page is adapted from the Emacs manual and the R FAQ

See Also

R FAQ, also sessionInfo() from which you may add to the bug report.


Send output to a character string or file

Description

Evaluates its arguments with the output being returned as a character string or sent to a file. Related to sink in the same way that with is related to attach.

Usage

capture.output(..., file = NULL, append = FALSE)

Arguments

... | Expressions to be evaluated
file | A file name or a connection, or NULL to return the output as a string. If the connection is not open it will be opened and then closed on exit.
append | Append or overwrite the file?

Value

A character string, or NULL if a file argument was supplied.

See Also

sink, textConnection

Examples

require(stats)
glmout <- capture.output(example(glm))
glmout[1:5]
capture.output(1+1, 2+2)
capture.output({1+1; 2+2})
## Not run:
## on Unix with enscript available
ps <- pipe("enscript -o tempout.ps","w")
capture.output(example(glm), file=ps)
close(ps)
## End(Not run)


Choose a List of Files Interactively

Description

Use a Windows file dialog to choose a list of zero or more files interactively.

Usage

choose.files(default = "", caption = "Select files",
             multi = TRUE, filters = Filters,
             index = nrow(Filters))

Filters

choose.dir(default = "", caption = "Select folder")

Arguments

default | which filename to show initially
caption | the caption on the file selection dialog
multi | whether to allow multiple files to be selected
filters | a matrix of filename filters (see Details)
index | which row of filters to use by default

Details

Unlike file.choose, choose.files will always attempt to return a character vector giving a list of files. If the user cancels the dialog, then zero files are returned, whereas file.choose would signal an error. choose.dir chooses a directory.

Windows file dialog boxes include a list of “filters”, which allow the file selection to be limited to files of specific types. The filters argument to choose.files allows the list of filters to be set. It should be an n by 2 character matrix. The first column gives, for each filter, the description the user will see, while the second column gives the mask(s) to select those files. If more than one mask is used, separate them by semicolons, with no spaces. The index argument chooses which filter will be used initially.

Filters is a matrix giving the descriptions and masks for the file types that R knows about. Print it to see typical formats for filter specifications. The examples below show how particular filters may be selected.

If you would like to display files in a particular directory, give a fully qualified file mask (e.g., 'c:\\*.*') in the default argument. If a directory is not given, the dialog will start in the current directory the first time, and “remember” the last directory on subsequent invocations.

Value

For choose.files, a character vector giving zero or more file paths.
For choose.dir, a character string, NA if ‘Cancel’ was selected.

See Also

file.choose

Examples

  if (interactive())
        choose.files(filters = Filters[c("zip", "All"),])

  if (interactive())
        choose.dir(getwd(), "Choose a suitable folder")


Select a CRAN Mirror

Description

Interact with the user to choose a CRAN mirror.

Usage

chooseCRANmirror(graphics = getOption("menu.graphics"))

Arguments

graphics Logical. If true use a Windows list box, otherwise use menu.

Details

A list of mirrors is stored in file ‘R_HOME/doc/CRAN_mirrors.csv’, but first an on-line list of current mirrors is consulted, and the file copy used only if the on-line list is inaccessible.

This function was originally written to support a Windows GUI menu item, but is also called by contrib.url if it finds the initial dummy value of options("repos").

Value

None. This function is invoked for its side effect of updating options("repos")

See Also

setRepositories, contrib.url.


Citing R and R Packages in Publications

Description

How to cite R and R packages in publications.

Usage

citation(package = "base", lib.loc = NULL)
## S3 method for class 'citation':
toBibtex(object, ...)
## S3 method for class 'citationList':
toBibtex(object, ...)

Arguments

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.
object | return object of citation.
... | currently not used.

Details

The R core development team and the very active community of package authors have invested a lot of time and effort in creating R as it is today. Please give credit where credit is due and cite R and R packages when you use them for data anlysis.

Execute function citation() for information on how to cite the base R system in publications. If the name of a non-base package is given, the function either returns the information contained in the CITATION file of the package or auto-generates citation information. In the latter case the package ‘DESCRIPTION’ file is parsed, the resulting citation object may be arbitrarily bad, but is quite useful (at least as a starting point) in most cases.

If only one reference is given, the print method shows both a text version and a BibTeX entry for it, if a package has more than one reference then only the text versions are shown. The BibTeX versions can be obtained using function toBibtex (see the examples below).

Value

An object of class "citationList".

See Also

citEntry

Examples

## the basic R reference
citation()

## references for a package -- might not have these installed
if(nchar(system.file(package="lattice"))) citation("lattice")
if(nchar(system.file(package="foreign"))) citation("foreign")

## extract the bibtex entry from the return value
x <- citation()
toBibtex(x)


Writing Package CITATION Files

Description

The ‘CITATION’ file of R packages contains an annotated list of references that should be used for citing the packages.

Usage

citEntry(entry, textVersion, header = NULL, footer = NULL, ...)
citHeader(...)
citFooter(...)
readCitationFile(file)

Arguments

entry | a character string with a BibTeX entry type
textVersion | a character string with a text representation of the reference
header | a character string with optional header text
footer | a character string with optional footer text
file | a file name
... | see details below

Details

The ‘CITATION’ file of an R package should be placed in the ‘inst’ subdirectory of the package source. The file is an R source file and may contain arbitrary R commands including conditionals and computations. The file is source()ed by the R parser in a temporary environment and all resulting objects of class "citation" (the return value of citEntry) are collected.

Typically the file will contain zero or more calls to citHeader, then one or more calls to citEntry, and finally zero or more calls to citFooter. citHeader and citFooter are simply wrappers to paste, and their ... argument is passed on to paste as is.

Value

citEntry returns an object of class "citation", readCitationFile returns an object of class "citationList".

Entry Types

citEntry creates "citation" objects, which are modeled after BibTeX entries. The entry should be a valid BibTeX entry type, e.g.,

article:
An article from a journal or magazine.
book:
A book with an explicit publisher.
inbook:
A part of a book, which may be a chapter (or section or whatever) and/or a range of pages.
incollection:
A part of a book having its own title.
inproceedings:
An article in a conference proceedings.
manual:
Technical documentation like a software manual.
mastersthesis:
A Master's thesis.
misc:
Use this type when nothing else fits.
phdthesis:
A PhD thesis.
proceedings:
The proceedings of a conference.
techreport:
A report published by a school or other institution, usually numbered within a series.
unpublished:
A document having an author and title, but not formally published.

Entry Fields

The ... argument of citEntry can be any number of BibTeX fields, including

address:
The address of the publisher or other type of institution.
author:
The name(s) of the author(s), either as a character string in the format described in the LaTeX book, or a personList object.
booktitle:
Title of a book, part of which is being cited.
chapter:
A chapter (or section or whatever) number.
editor:
Name(s) of editor(s), same format as author.
institution:
The publishing institution of a technical report.
journal:
A journal name.
note:
Any additional information that can help the reader. The first word should be capitalized.
number:
The number of a journal, magazine, technical report, or of a work in a series.
pages:
One or more page numbers or range of numbers.
publisher:
The publisher's name.
school:
The name of the school where a thesis was written.
series:
The name of a series or set of books.
title:
The work's title.
volume:
The volume of a journal or multi-volume book.
year:
The year of publication.

Examples

basecit <- system.file("CITATION", package="base")
source(basecit, echo=TRUE)
readCitationFile(basecit)


Read/Write to/from the Windows Clipboard

Description

Transfer text between a character vector and the Windows clipboard.

Usage

getClipboardFormats()
readClipboard(format = 1, raw = FALSE)
writeClipboard(str, format = 1)

Arguments

format | an integer giving the desired format.
raw | should the value be returned as a raw vector rather than a character vector?
str | a character vector or a raw vector.

Details

The Windows clipboard offers data in a number of formats. The standard formats are
CF_TEXT | 1
CF_BITMAP | 2
CF_METAFILEPICT | 3
CF_SYLK | 4
CF_DIF | 5
CF_TIFF | 6
CF_OEMTEXT | 7
CF_DIB | 8
CF_PALETTE | 9
CF_PENDATA | 10
CF_RIFF | 11
CF_WAVE | 12
CF_UNICODETEXT | 13
CF_ENHMETAFILE | 14
CF_HDROP | 15
CF_LOCALE | 16
CF_MAX | 17
CF_OWNERDISPLAY | 128
CF_DSPTEXT | 129
CF_DSPBITMAP | 130
CF_DSPMETAFILEPICT | 131
CF_DSPENHMETAFILE | 142
CF_PRIVATEFIRST | 512
CF_PRIVATELAST | 767
CF_GDIOBJFIRST | 768
CF_GDIOBJLAST | 1023
Applications normally make data available in one or more of these and possibly additional private formats. Use raw=TRUE to read binary formats, raw=FALSE (the default) for text formats.

The writeClipboard function will write a character vector as text, with standard CR-LF line terminators. It will copy a raw vector directly to the clipboard without any changes.

Value

For getClipboardFormats, an integer vector of available formats.
For readClipboard, a character vector by default, a raw vector if raw is TRUE, or NULL, if the format is unavailable.
For writeClipboard an invisible logical indicating success or failure.

See Also

file which can be used to set up a connection to a clipboard.


Close a Socket

Description

Closes the socket and frees the space in the file descriptor table. The port may not be freed immediately.

Usage

close.socket(socket, ...)

Arguments

socket | A socket object
... | further arguments passed to or from other methods.

Value

logical indicating success or failure

Author(s)

Thomas Lumley

See Also

make.socket, read.socket


Generate All Combinations of n Elements, Taken m at a Time

combn(utils) R Documentation

Generate All Combinations of n Elements Taken m at a Time

Description

Generate all combinations of the elements of x taken m at a time. If x is a positive integer, returns all combinations of the elements of seq(x) taken m at a time. If argument FUN is not NULL, applies a function given by the argument to each point. If simplify is FALSE, returns a list; otherwise returns an array, typically a matrix. ... are passed unchanged to the FUN function, if specified.

Usage

combn(x, m, FUN = NULL, simplify = TRUE, ...)

Arguments

x | vector source for combinations, or integer n for x <- seq(n).
m | number of elements to choose.
FUN | function to be applied to each combination; default NULL means the identity, i.e., to return the combination (vector of length m).
simplify | logical indicating if the result should be simplified to an array (typically a matrix); if FALSE, the function returns a list. Note that when simplify = TRUE as by default, the dimension of the result is simply determined from FUN(\emph{<1st combination>}), for efficiency reasons. This will badly fail if FUN(u) is not of constant length.
... | optionally, further arguments to FUN.

Value

a list or array (in nondegenerate cases), see the simplify argument above.

Author(s)

Scott Chasalow wrote the original in 1994 for S; R package combinat and documentation by Vince Carey stvjc@channing.harvard.edu; small changes by the R core team, notably to return an array in all cases of simplify = TRUE, e.g., for combn(5,5).

References

Nijenhuis, A. and Wilf, H.S. (1978) Combinatorial Algorithms for Computers and Calculators; Academic Press, NY.

See Also

choose for fast computation of the number of combinations. expand.grid for creating a data frame from all combinations of factors or vectors.

Examples

combn(letters[1:4], 2)
(m <- combn(10, 5, min))   # minimum value in each combination
mm <- combn(15, 6, function(x) matrix(x, 2,3))
stopifnot(round(choose(10,5)) == length(m),
          c(2,3, round(choose(15,6))) == dim(mm))

## Different way of encoding points:
combn(c(1,1,1,1,2,2,2,3,3,4), 3, tabulate, nbins = 4)

## Compute support points and (scaled) probabilities for a
## Multivariate-Hypergeometric(n = 3, N = c(4,3,2,1)) p.f.:
# table.mat(t(combn(c(1,1,1,1,2,2,2,3,3,4), 3, tabulate,nbins=4)))


Compare Two Package Version Numbers

Description

Compare two package version numbers to see which is later.

Usage

compareVersion(a, b)

Arguments

a, b Character strings representing package version numbers.

Details

R package version numbers are of the form x.y-z for integers x, y and z, with components after x optionally missing (in which case the version number is older than those with the components present).

Value

0 if the numbers are equal, -1 if b is later and 1 if a is later (analogous to the C function strcmp).

See Also

package_version, library, packageStatus.

Examples

compareVersion("1.0", "1.0-1")
compareVersion("7.2-0","7.1-12")


Data Sets

Description

Loads specified data sets, or list the available data sets.

Usage

data(..., list = character(0), package = NULL, lib.loc = NULL,
     verbose = getOption("verbose"), envir = .GlobalEnv)

Arguments

... | a sequence of names or literal character strings.
list | a character vector.
package | a character vector giving the package(s) to look in for data sets, or NULL. By default, all packages in the search path are used, then the ‘data’ subdirectory (if present) of the current working directory.
lib.loc | a character vector of directory names of R libraries, or NULL. The default value of NULL corresponds to all libraries currently known.
verbose | a logical. If TRUE, additional diagnostics are printed.
envir | the environment where the data should be loaded.

Details

Currently, four formats of data files are supported:

  1. files ending ‘.R’ or ‘.r’ are source()d in, with the R working directory changed temporarily to the directory containing the respective file.
  2. files ending ‘.RData’ or ‘.rda’ are load()ed.
  3. files ending ‘.tab’, ‘.txt’ or ‘.TXT’ are read using read.table(..., header = TRUE), and hence result in a data frame.
  4. files ending ‘.csv’ or ‘.CSV’ are read using read.table(..., header = TRUE, sep = ";"), and also result in a data frame.

If more than one matching file name is found, the first on this list is used.

The data sets to be loaded can be specified as a sequence of names or character strings, or as the character vector list, or as both.

For each given data set, the first two types (‘.R’ or ‘.r’, and ‘.RData’ or ‘.rda’ files) can create several variables in the load environment, which might all be named differently from the data set. The second two (‘.tab’, ‘.txt’, or ‘.TXT’, and ‘.csv’ or ‘.CSV’ files) will always result in the creation of a single variable with the same name as the data set.

If no data sets are specified, data lists the available data sets. It looks for a new-style data index in the ‘Meta’ or, if this is not found, an old-style ‘00Index’ file in the ‘data’ directory of each specified package, and uses these files to prepare a listing. If there is a ‘data’ area but no index, available data files for loading are computed and included in the listing, and a warning is given: such packages are incomplete. The information about available data sets is returned in an object of class "packageIQR". The structure of this class is experimental. Where the datasets have a different name from the argument that should be used to retrieve them the index will have an entry like beaver1 (beavers) which tells us that dataset beaver1 can be retrieved by the call data(beaver).

If lib.loc and package are both NULL (the default), the data sets are searched for in all the currently loaded packages then in the ‘data’ directory (if any) of the current working directory.

If lib.loc = NULL but package is specified as a character vector, the specified package(s) are searched for first amongst loaded packages and then in the default library/ies (see .libPaths).

If lib.loc is specified (and not NULL), packages are searched for in the specified library/ies, even if they are already loaded from another library.

To just look in the ‘data’ directory of the current working directory, set package = character(0) (and lib.loc = NULL, the default).

Value

a character vector of all data sets specified, or information about all available data sets in an object of class "packageIQR" if none were specified.

Note

The data files can be many small files. On some file systems it is desirable to save space, and the files in the ‘data’ directory of an installed package can be zipped up as a zip archive ‘Rdata.zip’. You will need to provide a single-column file ‘filelist’ of file names in that directory.

One can take advantage of the search order and the fact that a ‘.R’ file will change directory. If raw data are stored in ‘mydata.txt’ then one can set up ‘mydata.R’ to read ‘mydata.txt’ and pre-process it, e.g., using transform. For instance one can convert numeric vectors to factors with the appropriate labels. Thus, the ‘.R’ file can effectively contain a metadata specification for the plaintext formats.

See Also

help for obtaining documentation on data sets, save for creating the second (‘.rda’) kind of data, typically the most efficient one.

Examples

require(utils)
data()                       # list all available data sets
try(data(package = "rpart") )# list the data sets in the rpart package
data(USArrests, "VADeaths")  # load the data sets 'USArrests' and 'VADeaths'
help(USArrests)              # give information on data set 'USArrests'


Spreadsheet Interface for Entering Data

Description

A spreadsheet-like editor for entering or editing data.

Usage

data.entry(..., Modes = NULL, Names = NULL)
dataentry(data, modes)
de(..., Modes = list(), Names = NULL)

Arguments

... | A list of variables: currently these should be numeric or character vectors or list containing such vectors.
Modes | The modes to be used for the variables.
Names | The names to be used for the variables.
data | A list of numeric and/or character vectors.
modes | A list of length up to that of data giving the modes of (some of) the variables. list() is allowed.

Details

The data entry editor is only available on some platforms and GUIs. Where available it provides a means to visually edit a matrix or a collection of variables (including a data frame) as described in the “Notes” section.

data.entry has side effects, any changes made in the spreadsheet are reflected in the variables. The functions de, de.ncols, de.setup and de.restore are designed to help achieve these side effects. If the user passes in a matrix, X say, then the matrix is broken into columns before dataentry is called. Then on return the columns are collected and glued back together and the result assigned to the variable X. If you don't want this behaviour use dataentry directly.

The primitive function is dataentry. It takes a list of vectors of possibly different lengths and modes (the second argument) and opens a spreadsheet with these variables being the columns. The columns of the dataentry window are returned as vectors in a list when the spreadsheet is closed.

de.ncols counts the number of columns which are supplied as arguments to data.entry. It attempts to count columns in lists, matrices and vectors. de.setup sets things up so that on return the columns can be regrouped and reassigned to the correct name. This is handled by de.restore.

Value

de and dataentry return the edited value of their arguments. data.entry invisibly returns a vector of variable names but its main value is its side effect of assigning new version of those variables in the user's workspace.

Note

The details of interface to the data grid may differ by platform and GUI. The following description applies to the GraphApp-based implementation under Windows.

You can navigate around the grid using the cursor keys or by clicking with the (left) mouse button on any cell. The active cell is highlighted by thickening the surrounding rectangle. Moving to the right or down will scroll the grid as needed: there is no constraint to the rows or columns currently in use.

There are alternative ways to navigate using the keys. Return and (keypad) Enter and LineFeed all move down. Tab moves right and Shift-Tab move left. Home moves to the top left.

PageDown or Control-F moves down a page, and PageUp or Control-B up by a page. End will show the last used column and the last few rows used (in any column).

Using any other key starts an editing process on the currently selected cell: moving away from that cell enters the edited value whereas Esc cancels the edit and restores the previous value. When the editing process starts the cell is cleared. The cursor changes to an I-beam to indicate that the cell is in enter mode. In numerical columns (the default) only letters making up a valid number (including -.eE) are accepted, and entering an invalid edited value (such as blank) enters NA in that cell. The last entered value can be deleted using the BackSpace or Del(ete) key. Only a limited number of characters (currently 29) can be entered in a cell, and if necessary only the start or end of the string will be displayed, with the omissions indicated by > or <. (The start is shown except when editing.)

Double-clicking on a cell selects the cell and makes it into an editable field (a cursor will appear at the end of the text and it will change to the text highlight colour). The edited text is entered by selecting another cell, for example by hitting Return. There is no way to cancel the edits. The field will be expanded to the right if necessary to accommodate existing long strings, so it is preferable not to edit in the right-most displayed column. (The editable field is itself scrollable.)

Entering a value in a cell further down a column than the last used cell extends the variable and fills the gap (if any) by NAs (not shown on screen).

The column names can only be selected by clicking in them. This gives a popup menu to select the column type (currently Real (numeric) or Character) or to change the name. Changing the type converts the current contents of the column (and converting from Character to Real may generate NAs.) Enter the changes made in the popup window by clicking on its close box.

New columns are created by entering values in them (and not by just assigning a new name). The mode of the column is auto-detected from the first value entered: if this is a valid number it gives a numeric column. Unused columns are ignored, so adding data in var5 to a three-column grid adds one extra variable, not two.

There is a popup-menu accessed by right-clicking anywhere in the window that refers to the currently selected cell. This can copy the value to or paste from the clipboard, or paste in common values in that column. Copying and pasting can also be accessed by the usual keyboard shortcuts Control-C and Control-V.

Columns can be resized by selecting and dragging a line (the cursor will change) within limits: columns must be between 4 and 50 chars wide. The Autosize item on the popup menu will resize the currently selected column.

Control-L will refresh the display, recalculating field widths to fit the current entries.

In the default mode the column widths are chosen to fit the contents of each column, with a default of 10 characters for empty columns. you can specify fixed column widths by setting option de.cellwidth to the required fixed width (in characters). (set it to zero to return to variable widths). The displayed width of any field is limited to 50 characters (and by the window width).

See Also

vi, edit: edit uses dataentry to edit data frames.

Examples

# call data entry with variables x and y
## Not run: data.entry(x,y)


Post-Mortem Debugging

Description

Functions to dump the evaluation environments (frames) and to examine dumped frames.

Usage

dump.frames(dumpto = "last.dump", to.file = FALSE)
debugger(dump = last.dump)

Arguments

dumpto | a character string. The name of the object or file to dump to.
to.file | logical. Should the dump be to an R object or to a file?
dump | An R dump object created by dump.frames.

Details

To use post-mortem debugging, set the option error to be a call to dump.frames. By default this dumps to an R object "last.dump" in the workspace, but it can be set to dump to a file (as dump of the object produced by a call to save). The dumped object contain the call stack, the active environments and the last error message as returned by geterrmessage.

When dumping to file, dumpto gives the name of the dumped object and the file name has .rda appended.

A dump object of class "dump.frames" can be examined by calling debugger. This will give the error message and a list of environments from which to select repeatedly. When an environment is selected, it is copied and the browser called from within the copy.

If dump.frames is installed as the error handler, execution will continue even in non-interactive sessions. See the examples for how to dump and then quit.

Value

None.

Note

Functions such as sys.parent and environment applied to closures will not work correctly inside debugger.

If the error occurred when computing the default value of a formal argument the debugger will report "recursive default argument reference" when trying to examine that environment.

Of course post-mortem debugging will not work if R is too damaged to produce and save the dump, for example if it has run out of workspace.

References

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

See Also

options for setting error options; recover is an interactive debugger working similarly to debugger but directly after the error occurs.

Examples

## Not run:
options(error=quote(dump.frames("testdump", TRUE)))

f <- function() {
    g <- function() stop("test dump.frames")
    g()
}
f()   # will generate a dump on file "testdump.rda"
options(error=NULL)

## possibly in another R session
load("testdump.rda")
debugger(testdump)
Available environments had calls:
1: f()
2: g()
3: stop("test dump.frames")

Enter an environment number, or 0 to exit
Selection: 1
Browsing in the environment with call:
f()
Called from: debugger.look(ind)
Browse[1]> ls()
[1] "g"
Browse[1]> g
function() stop("test dump.frames")
<environment: 759818>
Browse[1]>
Available environments had calls:
1: f()
2: g()
3: stop("test dump.frames")

Enter an environment number, or 0 to exit
Selection: 0

## A possible setting for non-interactive sessions
options(error=quote({dump.frames(to.file=TRUE); q()}))
## End(Not run)


Demonstrations of R Functionality

Description

demo is a user-friendly interface to running some demonstration R scripts. demo() gives the list of available topics.

Usage

demo(topic, package = NULL, lib.loc = NULL,
     character.only = FALSE, verbose = getOption("verbose"))

Arguments

topic | the topic which should be demonstrated, given as a name or literal character string, or a character string, depending on whether character.only is FALSE (default) or TRUE. If omitted, the list of available topics is displayed.
package | a character vector giving the packages to look into for demos, or NULL. By default, all packages in the search path are used.
lib.loc | a character vector of directory 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.
character.only | logical; if TRUE, use topic as character string.
verbose | a logical. If TRUE, additional diagnostics are printed.

Details

If no topics are given, demo lists the available demos. The corresponding information is returned in an object of class "packageIQR". The structure of this class is experimental. In earlier versions of R, an empty character vector was returned along with listing available demos.

See Also

source which is called by demo.

Examples

demo() # for attached packages

## All available demos:
demo(package = .packages(all.available = TRUE))

demo(lm.glm, package="stats")
## Not run:
 ch <- "scoping"
 demo(ch, character = TRUE)
## End(Not run)


DLL Version Information

Description

Return the version of the package and the version of R used to build the DLL, if available (usually only since R version 1.2.0).

Usage

DLL.version(path)

Arguments

path character vector of length one giving the complete path to the DLL.

Value

If the DLL does not exist, NULL.
A character vector of two, giving the DLL version and the version of R used to build the DLL. If the information is not available, the corresponding string is empty.

Examples

DLL.version(file.path(R.home(), "bin/R.dll"))
DLL.version(file.path(R.home(), "library/stats/libs/stats.dll"))


Download File from the Internet

Description

This function can be used to download a file from the Internet.

Usage

download.file(url, destfile, method, quiet = FALSE, mode = "w",
              cacheOK = TRUE)

Arguments

url | A character string naming the URL of a resource to be downloaded.
destfile | A character string with the name where the downloaded file is saved. Tilde-expansion is performed.
method | Method to be used for downloading files. Currently download methods "internal", "wget" and "lynx" are available, and there is a value "auto": see Details. The method can also be set through the option "download.file.method": see options().
quiet | If TRUE, suppress status messages (if any).
mode | character. The mode with which to write the file. Useful values are "w", "wb" (binary), "a" (append) and "ab". Only used for the "internal" method.
cacheOK | logical. Is a server-side cached value acceptable? Implemented for the "internal" and "wget" methods.

Details

The function download.file can be used to download a single file as described by url from the internet and store it in destfile. The url must start with a scheme such as "http://", "ftp://" or "file://".

If method = "auto" is chosen (the default), the internal method is used on Windows.

cacheOK = FALSE is useful for "http://" URLs, and will attempt to get a copy directly from the site rather than from an intermediate cache. (Not all platforms support it.) It is used by available.packages.

The remaining details apply to method "internal" only.

See url for how "file://" URLs are interpreted, especially on Windows. This function does decode encoded URLs.

The timeout for many parts of the transfer can be set by the option timeout which defaults to 60 seconds.

The level of detail provided during transfer can be set by the quiet argument and the internet.info option. The details depend on the platform and scheme, but setting internet.info to 0 gives all available details, including all server responses. Using 2 (the default) gives only serious messages, and 3 or more suppresses all messages.

A progress bar tracks the transfer. If the file length is known, the full width of the bar is the known length. Otherwise the initial width represents 100Kbytes and is doubled whenever the current width is exceeded.

There is an alternative method if you have Internet Explorer 4 or later installed. You can use the flag --internet2, when the ‘Internet Options’ of the system are used to choose proxies and so on; these are set in the Control Panel and are those used for Internet Explorer. This version does not support cacheOK = FALSE.

Method "wget" can be used with proxy firewalls which require user/password authentication if proper values are stored in the configuration file for wget.

Value

An (invisible) integer code, 0 for success and non-zero for failure. For the "wget" and "lynx" methods this is the status code returned by the external program. The "internal" method can return 1, but will in most cases throw an error.

Setting Proxies

This applies to the internal code only.

Proxies can be specified via environment variables. Setting "no_proxy" stops any proxy being tried. Otherwise the setting of "http_proxy" or "ftp_proxy" (or failing that, the all upper-case version) is consulted and if non-empty used as a proxy site. For FTP transfers, the username and password on the proxy can be specified by "ftp_proxy_user" and "ftp_proxy_password". The form of "http_proxy" should be "http://proxy.dom.com/" or "http://proxy.dom.com:8080/" where the port defaults to 80 and the trailing slash may be omitted. For "ftp_proxy" use the form "ftp://proxy.dom.com:3128/" where the default port is 21. These environment variables must be set before the download code is first used: they cannot be altered later by calling Sys.putenv.

Usernames and passwords can be set for HTTP proxy transfers via environment variable http_proxy_user in the form user:passwd. Alternatively, "http_proxy" can be of the form "http://user:pass@proxy.dom.com:8080/" for compatibility with wget. Only the HTTP/1.0 basic authentication scheme is supported. Under Windows, if "http_proxy_user" is set to "ask" then a dialog box will come up for the user to enter the username and password. NB: you will be given only one opportunity to enter this, but if proxy authentication is required and fails there will be one further prompt per download.

Note

Methods "wget" and "lynx" are for historical compatibility. They will block all other activity on the R process.

For methods "wget" and "lynx" a system call is made to the tool given by method, and the respective program must be installed on your system and be in the search path for executables.

See Also

options to set the timeout and internet.info options.

url for a finer-grained way to read data from URLs.

url.show, available.packages, download.packages for applications


Invoke a Text Editor

Description

Invoke a text editor on an R object.

Usage

## Default S3 method:
edit(name = NULL, file = "", title = NULL,
     editor = getOption("editor"), ...)

vi(name = NULL, file = "")
emacs(name = NULL, file = "")
pico(name = NULL, file = "")
xemacs(name = NULL, file = "")
xedit(name = NULL, file = "")

Arguments

name | a named object that you want to edit. If name is missing then the file specified by file is opened for editing.
file | a string naming the file to write the edited version to.
title | a display name for the object being edited.
editor | a string naming the text editor you want to use. On Unix the default is set from the environment variables EDITOR or VISUAL if either is set, otherwise vi is used. On Windows it defaults to notepad.
... | further arguments to be passed to or from methods.

Details

edit invokes the text editor specified by editor with the object name to be edited. It is a generic function, currently with a default method and one for data frames and matrices.

data.entry can be used to edit data, and is used by edit to edit matrices and data frames on systems for which data.entry is available.

It is important to realize that edit does not change the object called name. Instead, a copy of name is made and it is that copy which is changed. Should you want the changes to apply to the object name you must assign the result of edit to name. (Try fix if you want to make permanent changes to an object.)

In the form edit(name), edit deparses name into a temporary file and invokes the editor editor on this file. Quitting from the editor causes file to be parsed and that value returned. Should an error occur in parsing, possibly due to incorrect syntax, no value is returned. Calling edit(), with no arguments, will result in the temporary file being reopened for further editing.

Currently only the internal editor in Windows makes use of the title option; it displays the given name in the window header.

Note

The functions vi, emacs, pico, xemacs, xedit rely on the corresponding editor being available and being on the path. This is system-dependent.

See Also

edit.data.frame, data.entry, fix.

Examples

## Not run:
# use xedit on the function mean and assign the changes
mean <- edit(mean, editor = "xedit")

# use vi on mean and write the result to file mean.out
vi(mean, file = "mean.out")
## End(Not run)


Edit Data Frames and Matrices

Description

Use data editor on data frame or matrix contents.

Usage

## S3 method for class 'data.frame':
edit(name, factor.mode = c("character", "numeric"),
     edit.row.names = any(row.names(name) != 1:nrow(name)), ...)

## S3 method for class 'matrix':
edit(name, edit.row.names = !is.null(dn[[1]]), ...)

Arguments

name | A data frame or matrix.
factor.mode | How to handle factors (as integers or using character levels) in a data frame.
edit.row.names | logical. Show the row names be displayed as a separate editable column?
... | further arguments passed to or from other methods.

Details

At present, this only works on simple data frames containing numeric, logical or character vectors and factors. Factors are represented in the spreadsheet as either numeric vectors (which is more suitable for data entry) or character vectors (better for browsing). After editing, vectors are padded with NA to have the same length and factor attributes are restored. The set of factor levels can not be changed by editing in numeric mode; invalid levels are changed to NA and a warning is issued. If new factor levels are introduced in character mode, they are added at the end of the list of levels in the order in which they encountered.

It is possible to use the data-editor's facilities to select the mode of columns to swap between numerical and factor columns in a data frame. Changing any column in a numerical matrix to character will cause the result to be coerced to a character matrix. Changing the mode of logical columns is not supported.

The columns are coerced on input to numeric unless logical, character or factor (which may well not be what you want).

For a data frame, the row names will be taken from the original object if edit.row.names = FALSE and the number of rows is unchanged, and from the edited output if edit.row.names = TRUE and there are no duplicates. (If the row.names column is incomplete, it is extended by entries like row223.) In all other cases the row names are replaced by seq(length=nrows).

For a matrix, colnames will be added (of the form col7) if needed. The rownames will be taken from the original object if edit.row.names = FALSE and the number of rows is unchanged (otherwise NULL), and from the edited output if edit.row.names = TRUE. (If the row.names column is incomplete, it is extended by entries like row223.)

Value

The edited data frame.

Note

fix(dataframe) works for in-place editing by calling this function.

If the data editor is not available, a dump of the object is presented for editing using the default method of edit.

At present the data editor is limited to 65535 rows.

Author(s)

Peter Dalgaard

See Also

data.entry, edit

Examples

## Not run:
edit(InsectSprays)
edit(InsectSprays, factor.mode="numeric")
## End(Not run)


Run an Examples Section from the Online Help

Description

Run all the R code from the Examples part of R's online help topic topic with two possible exceptions, dontrun and dontshow, see Details below.

Usage

example(topic, package = NULL, lib.loc = NULL,
        local = FALSE, echo = TRUE, verbose = getOption("verbose"),
        setRNG = FALSE, ask = getOption("example.ask"),
        prompt.echo = paste(abbreviate(topic, 6),"> ", sep=""))

Arguments

topic | name or literal character string: the online help topic the examples of which should be run.
package | a character vector giving the package names to look into for example code, or NULL. By default, all packages in the search path are used.
lib.loc | a character vector of directory 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.
local | logical: if TRUE evaluate locally, if FALSE evaluate in the workspace.
echo | logical; if TRUE, show the R input when sourcing.
verbose | logical; if TRUE, show even more when running example code.
setRNG | logical or expression; if not FALSE, the random number generator state is saved, then initialized to a specified state, the example is run and the (saved) state is restored. setRNG = TRUE sets the same state as R CMD check does for running a package's examples. This is currently equivalent to setRNG = {RNGkind("default", "default"); set.seed(1)}.
ask | logical (or "default") indicating if par(ask=TRUE) should be called before graphical output happens from the example code. The value "default" (the factory-fresh default) means to ask if echo == TRUE and the graphics device appears to be interactive. This parameter applies both to any currently opened device and to any devices opened by the example code.
prompt.echo | character; gives the prompt to be used if echo = TRUE.

Details

If lib.loc is not specified, the packages are searched for amongst those already loaded, then in the specified libraries. If lib.loc is specified, they are searched for only in the specified libraries, even if they are already loaded from another library.

An attempt is made to load the package before running the examples, but this will not replace a package loaded from another location.

If local=TRUE objects are not created in the workspace and so not available for examination after example completes: on the other hand they cannot clobber objects of the same name in the workspace.

As detailed in the manual Writing R Extensions, the author of the help page can markup parts of the examples for two exception rules

dontrun
encloses code that should not be run.
dontshow
encloses code that is invisible on help pages, but will be run both by the package checking tools, and the example() function. This was previously testonly, and that form is still accepted.

If the examples file contains non-ASCII characters the encoding used will matter. If in a UTF-8 locale example first tries UTF-8 and then Latin-1. (This can be overridden by setting the encoding in the .Rd file.)

Value

The value of the last evaluated expression.

Note

The examples can be many small files. On some file systems it is desirable to save space, and the files in the ‘R-ex’ directory of an installed package can be zipped up as a zip archive ‘Rex.zip’.

Author(s)

Martin Maechler and others

See Also

demo

Examples

example(InsectSprays)
## force use of the standard package 'stats':
example("smooth", package="stats", lib.loc=.Library)

## set RNG *before* example as when R CMD check is run:

r1 <- example(quantile, setRNG = TRUE)
x1 <- rnorm(1)
u <- runif(1)
## identical random numbers
r2 <- example(quantile, setRNG = TRUE)
x2 <- rnorm(1)
stopifnot(identical(r1, r2))
## but x1 and x2 differ since the RNG state from before example()
## differs and is restored!
x1; x2


Edit One or More Files

Description

Edit one or more files in a text editor.

Usage

file.edit(..., title = file, editor = getOption("editor"))

Arguments

... | one or more character vectors containing the names of the files to be edited.
title | the title to use in the editor; defaults to the filename.
editor | the text editor to be used.

Details

The behaviour of this function is very system dependent. Currently files can be opened only one at a time on Unix; on Windows, the internal editor allows multiple files to be opened, but has a limit of 50 simultaneous edit windows.

The title argument is used for the window caption in Windows, and is ignored on other platforms.

See Also

files, file.show, edit, fix,

Examples

## Not run:
# open two R scripts for editing
file.edit("script1.R", "script2.R")
## End(Not run)


Fix an Object

Description

fix invokes edit on x and then assigns the new (edited) version of x in the user's workspace.

Usage

fix(x, ...)

Arguments

x | the name of an R object, as a name or a character string.
... | arguments to pass to editor: see edit.

Details

The name supplied as x need not exist as an R object, in which case a function with no arguments and an empty body is supplied for editing.

See Also

edit, edit.data.frame

Examples

## Not run:
 ## Assume 'my.fun' is a user defined function :
 fix(my.fun)
 ## now my.fun is changed
 ## Also,
 fix(my.data.frame) # calls up data editor
 fix(my.data.frame, factor.mode="char") # use of ...
## End(Not run)


Flush Output to A Console

Description

This does nothing except on console-based versions of R. On the Mac OS X and Windows GUIs, it ensures that the display of output in the console is current, even if output buffering is on.

Usage

flush.console()


Retrieve an R Object, Including from a Namespace

getAnywhere(utils) R Documentation

Retrieve an R Object Including from a Namespace

Description

These functions locates all objects with name matching its argument, whether visible on the search path, registered as an S3 method or in a namespace but not exported. getAnywhere() returns the objects and argsAnywhere() returns the arguments of any objects that are functions.

Usage

getAnywhere(x)
argsAnywhere(x)

Arguments

x a character string or name.

Details

The function looks at all loaded namespaces, whether or not they are associated with a package on the search list.

Where functions are found as an S3 method, an attempt is made to find which namespace registered them. This may not be correct, especially if a namespace is unloaded.

Value

For getAnywhere() an object of class "getAnywhere". This is a list with components

name | the name searched for.
objs | a list of objects found
where | a character vector explaining where the object(s) were found
visible | logical: is the object visible
dups | logical: is the object identical to one earlier in the list.

Normally the structure will be hidden by the print method. There is a [ method to extract one or more of the objects found.
For argsAnywhere() one or more argument lists as returned by args.

See Also

get, getFromNamespace, args

Examples

getAnywhere("format.dist")
getAnywhere("simpleLoess") # not exported from stats
argsAnywhere(format.dist)


Utility functions for Developing Namespaces

Description

Utility functions to access and replace the non-exported functions in a namespace, for use in developing packages with namespaces.

Usage

getFromNamespace(x, ns, pos = -1, envir = as.environment(pos))
assignInNamespace(x, value, ns, pos = -1, envir = as.environment(pos))
fixInNamespace(x, ns, pos = -1, envir = as.environment(pos), ...)

Arguments

x | an object name (given as a character string).
value | an R object.
ns | a namespace, or character string giving the namespace.
pos | where to look for the object: see get.
envir | an alternative way to specify an environment to look in.
... | arguments to pass to the editor: see edit.

Details

The namespace can be specified in several ways. Using, for example, ns = "stats" is the most direct, but a loaded package with a namespace can be specified via any of the methods used for get: ns can also be the environment printed as <namespace:foo>.

getFromNamespace is similar to (but predates) the ::: operator, but is more flexible in how the namespace is specified.

fixInNamespace invokes edit on the object named x and assigns the revised object in place of the original object. For compatibility with fix, x can be unquoted.

Value

getFromNamespace returns the object found (or gives an error).
assignInNamespace and fixInNamespace are invoked for their side effect of changing the object in the namespace.

Note

assignInNamespace and fixInNamespace change the copy in the namespace, but not any copies already exported from the namespace, in particular an object of that name in the package (if already attached) and any copies already imported into other namespaces. They are really intended to be used only for objects which are not exported from the namespace. They do attempt to alter a copy registered as an S3 method if one is found.

See Also

get, fix, getS3method

Examples

getFromNamespace("findGeneric", "utils")
## Not run:
fixInNamespace("predict.ppr", "stats")
stats:::predict.ppr
getS3method("predict", "ppr")
## alternatively
fixInNamespace("predict.ppr", pos = 3)
fixInNamespace("predict.ppr", pos = "package:stats")
## End(Not run)


Get An S3 Method

Description

Get a method for an S3 generic, possibly from a namespace.

Usage

getS3method(f, class, optional = FALSE)

Arguments

f | character: name of the generic.
class | character: name of the class.
optional | logical: should failure to find the generic or a method be allowed?

Details

S3 methods may be hidden in packages with namespaces, and will not then be found by get: this function can retrieve such functions, primarily for debugging purposes.

Value

The function found, or NULL if no function is found and optional = TRUE.

See Also

methods, get

Examples

require(stats)
exists("predict.ppr") # false
getS3method("predict", "ppr")


Get a Windows Handle

Description

Get the Windows handle of a window or the R process.

Usage

getWindowsHandle(which = "Console")

Arguments

which A string (see below), or the number of a graphics device window

Details

getWindowsHandle gets the Windows handle or process ID. Possible choices for which are:
"Console" | The console window handle.
"Frame" | The MDI frame window handle.
"Process" | The process pseudo-handle.
"ProcessId" | The process identifier.
A device number | The window handle of a graphics device

These values are not normally useful to users, but may be used by developers making add-ons to R{}.

A zero is returned for the Frame handle if not running in MDI mode, for the Console handle when running Rterm, for any unrecognized string for which, or for a graphics device with no corresponding window.

Currently other windows (help browsers, etc.) are not accessible through this function, but there are plans to make them available later.

Value

A one element integer vector holding the Windows handle.

See Also

getIdentification

Examples

getWindowsHandle()


Change Wildcard or Globbing Pattern into Regular Expression

Description

Change wildcard aka globbing (or “ls” like) pattern into the corresponding regular expression (regexp).

Usage

glob2rx(pattern, trim.head = FALSE, trim.tail = TRUE)

Arguments

pattern | character vector
trim.head | logical specifying if leading "^.*" should be trimmed from the result.
trim.tail | logical specifying if trailing ".*$" should be trimmed from the result.

Details

This takes a wildcard as used by most shells and returns an equivalent regular expression. ? is mapped to . (match a single character), * to .* (match any string, including an empty one), and the pattern is anchored (it must start at the beginning and end at the end). Optionally, the resulting regexp is simplified.

Value

A character vector of the same length as the input pattern where each “wild card” is translated to the corresponding regular expression.

Author(s)

Martin Maechler, Unix/sed based version, 1991; current: 2004

See Also

regexp about regular expression, sub, etc about substitutions using regexps.

Examples

stopifnot(glob2rx("abc.*") == "^abc\\.",
          glob2rx("a?b.*") == "^a.b\\.",
          glob2rx("a?b.*", trim.tail=FALSE) == "^a.b\\..*$",
          glob2rx("*.doc") == "^.*\\.doc$",
          glob2rx("*.doc", trim.head=TRUE) == "\\.doc$",
          glob2rx("*.t*")  == "^.*\\.t",
          glob2rx("*.t??") == "^.*\\.t..$"
)


Return the First or Last Part of an Object

Description

Returns the first or last parts of a vector, matrix, table, data frame or function. Since head() and tail() are generic functions, they may also have been extended to other classes.

Usage

head(x, ...)
## Default S3 method:
head(x, n = 6, ...)
## S3 method for class 'data.frame':
head(x, n = 6, ...)
## S3 method for class 'matrix':
head(x, n = 6, ...)
## S3 method for class 'ftable':
head(x, n = 6, ...)
## S3 method for class 'table':
head(x, n = 6, ...)
## S3 method for class 'function':
head(x, n = 6, ...)

tail(x, ...)
## Default S3 method:
tail(x, n = 6, ...)
## S3 method for class 'data.frame':
tail(x, n = 6, ...)
## S3 method for class 'matrix':
tail(x, n = 6, addrownums = TRUE, ...)
## S3 method for class 'ftable':
tail(x, n = 6, addrownums = FALSE, ...)
## S3 method for class 'table':
tail(x, n = 6, addrownums = TRUE, ...)
## S3 method for class 'function':
tail(x, n = 6, ...)

Arguments

x | an object
n | a single integer. If positive, size for the resulting object: number of elements for a vector (including lists), rows for a matrix or data frame or lines for a function. If negative, all but the n last/first number of elements of x.
addrownums | if there are no row names, create them from the row numbers.
... | arguments to be passed to or from other methods.

Details

For matrices, 2-dim tables and data frames, head() (tail()) returns the first (last) n rows when n > 0 or all but the last (first) n rows when n < 0. head.matrix() and tail.matrix() are exported. For functions, the lines of the deparsed function are returned as character strings.

If a matrix has no row names, then tail() will add row names of the form "[n,]" to the result, so that it looks similar to the last lines of x when printed. Setting addrownums = FALSE suppresses this behaviour.

Value

An object (usually) like x but generally smaller. For ftable objects x, a transformed format(x).

Author(s)

Patrick Burns, improved and corrected by R-Core. Negative argument added by Vincent Goulet.

Examples

head(letters)
head(letters, n = -6)

head(freeny.x, n = 10)
head(freeny.y)

tail(letters)
tail(letters, n = -6)

tail(freeny.x)
tail(freeny.y)

tail(library)

head(ftable(Titanic))


Documentation

Description

These functions provide access to documentation. Documentation on a topic with name name (typically, an R object or a data set) can be printed with either help(name) or ?name.

Usage

help(topic, offline = FALSE, package = NULL,
     lib.loc = NULL, verbose = getOption("verbose"),
     try.all.packages = getOption("help.try.all.packages"),
     chmhelp = getOption("chmhelp"),
     htmlhelp = getOption("htmlhelp"),
     pager = getOption("pager"))

?topic

type?topic

Arguments

topic | usually, the name on which documentation is sought. The name may be quoted or unquoted (but note that if topic is the name of a variable containing a character string documentation is provided for the name, not for the character string). The topic argument may also be a function call, to ask for documentation on a corresponding method. See the section on method documentation. See Details for what happens if this is omitted.
offline | a logical indicating whether documentation should be displayed on-line to the screen (the default) or hardcopy of it should be produced.
package | a name or character vector giving the packages to look into for documentation, or NULL. By default, all packages in the search path are used.
lib.loc | a character vector of directory 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.
verbose | logical; if TRUE, the file name is reported.
try.all.packages | logical; see Note.
chmhelp | logical (or NULL). Only relevant under Windows. If TRUE the Compiled HTML version of the help on the topic will be shown in a help viewer.
htmlhelp | logical (or NULL). If TRUE, the HTML version of the help on the topic will be shown in a browser specified by options("browser") or the file-association mechanism.
pager | the pager to be used for file.show.
type | the special type of documentation to use for this topic; for example, if the type is class, documentation is provided for the class with name topic. The function topicName returns the actual name used in this case. See the section on method documentation for the uses of type to get help on formal methods.

Details

topic is not optional: if it is omitted R will give a hint as to suitable topics if a package is specified, to available packages if lib.loc only is specified, and help on help itself if nothing is specified. (In all cases this will be text help.)

In the case of unary and binary operators and control-flow special forms (including if, for and function), the topic may need to be quoted.

If multiple help files matching topic are found, in interactive use a menu is presented for the user to choose one: otherwise the first on the search path is used. (The menu will be a graphical menu if possible if getOption("menu.graphics") is true, the default.)

If offline is TRUE, hardcopy of the documentation is produced by running the LaTeX version of the help page through latex (note that LaTeX 2e is needed). You need to customize the file ‘R_HOME/bin/helpPRINT.bat’ which contains an example. The appearance of the output can be customized through a file ‘Rhelp.cfg’ somewhere in your LaTeX search path.

If LaTeX versions of help pages were not built at the installation of the package, the print method will ask if conversion with R CMD Rdconv (which requires Perl) should be attempted.

S4 Method Documentation

The authors of formal (‘S4’) methods can provide documentation on specific methods, as well as overall documentation on the methods of a particular function. The "?" operator allows access to this documentation in three ways.

The expression methods ? f will look for the overall documentation methods for the function f. Currently, this means the documentation file containing the alias f-methods.

There are two different ways to look for documentation on a particular method. The first is to supply the topic argument in the form of a function call, omitting the type argument. The effect is to look for documentation on the method that would be used if this function call were actually evaluated. See the examples below. If the function is not a generic (no S4 methods are defined for it), the help reverts to documentation on the function name.

The "?" operator can also be called with type supplied as "method"; in this case also, the topic argument is a function call, but the arguments are now interpreted as specifying the class of the argument, not the actual expression that will appear in a real call to the function. See the examples below.

The first approach will be tedious if the actual call involves complicated expressions, and may be slow if the arguments take a long time to evaluate. The second approach avoids these difficulties, but you do have to know what the classes of the actual arguments will be when they are evaluated.

Both approaches make use of any inherited methods; the signature of the method to be looked up is found by using selectMethod (see the documentation for getMethod).

Note

Unless lib.loc is specified explicitly, the loaded packages are searched before those in the specified libraries. This ensures that if a library is loaded from a library not in the known library trees, then the help from the loaded library is used. If lib.loc is specified explicitly, the loaded packages are not searched.

If this search fails and argument try.all.packages is TRUE and neither packages nor lib.loc is specified, then all the packages in the known library trees are searched for help on topic and a list of (any) packages where help may be found is printed (but no help is shown). N.B. searching all packages can be slow.

The help files can be many small files. On some file systems it is desirable to save space, and the text files in the ‘help’ directory of an installed package can be zipped up as a zip archive ‘Rhelp.zip’. Ensure that file ‘AnIndex’ remains un-zipped. Similarly, all the files in the ‘latex’ directory can be zipped to ‘Rhelp.zip’. This is done on Windows for the larger packages.

References

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

See Also

help.search() for finding help pages on a “vague”
topic;
help.start() which opens the HTML version of the R
help pages;
library() for listing available packages and the
user-level objects they contain;
data() for listing available data sets;
methods().

See prompt() to get a prototype for writing help pages of private packages.

Examples

help()
help(help)              # the same

help(lapply)
?lapply                 # the same

help("for")             # or ?"for", but the quotes are needed
?"+"

help(package="splines") # get help even when package is not loaded

data()                  # list all available data sets
?women                  # information about data set "women"

topi <- "women"
## Not run: help(topi) ##--> Error: No documentation for 'topi'

try(help("bs", try.all.packages=FALSE)) # reports not found (an error)
help("bs", try.all.packages=TRUE) # reports can be found in package 'splines'

## Not run:
require(methods)
## define a S4 generic function and some methods
combo <- function(x, y) c(x, y)
setGeneric("combo")
setMethod("combo", c("numeric", "numeric"), function(x, y) x+y)

## assume we have written some documentation for combo, and its methods ....

?combo  ## produces the function documentation

methods?combo  ## looks for the overall methods documentation

method?combo("numeric", "numeric")  ## documentation for the method above

?combo(1:10, rnorm(10))  ## ... the same method, selected according to
                         ## the arguments (one integer, the other numeric)

?combo(1:10, letters)    ## documentation for the default method
## End(Not run)


Search the Help System

Description

Allows for searching the help system for documentation matching a given character string in the (file) name, alias, title, concept or keyword entries (or any combination thereof), using either fuzzy matching or regular expression matching. Names and titles of the matched help entries are displayed nicely formatted.

Usage

help.search(pattern, fields = c("alias", "concept", "title"),
            apropos, keyword, whatis, ignore.case = TRUE,
            package = NULL, lib.loc = NULL,
            help.db = getOption("help.db"),
            verbose = getOption("verbose"),
            rebuild = FALSE, agrep = NULL)

Arguments

pattern | a character string to be matched in the specified fields. If this is given, the arguments apropos, keyword, and whatis are ignored.
fields | a character vector specifying the fields of the help data bases to be searched. The entries must be abbreviations of "name", "title", "alias", "concept", and "keyword", corresponding to the help page's (file) name, its title, the topics and concepts it provides documentation for, and the keywords it can be classified to.
apropos | a character string to be matched in the help page topics and title.
keyword | a character string to be matched in the help page ‘keywords’. ‘Keywords’ are really categories: the standard categories are listed in file ‘RHOME/doc/KEYWORDS’ (see also the example) and some package writers have defined their own. If keyword is specified, agrep defaults to FALSE.
whatis | a character string to be matched in the help page topics.
ignore.case | a logical. If TRUE, case is ignored during matching; if FALSE, pattern matching is case sensitive.
package | a character vector with the names of packages to search through, or NULL in which case all available packages in the library trees specified by lib.loc are searched.
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.
help.db | a character string giving the file path to a previously built and saved help data base, or NULL.
verbose | logical; if TRUE, the search process is traced.
rebuild | a logical indicating whether the help data base should be rebuilt. This will be done automatically if lib.loc or the search path is changed, or if package is used and a value is not found.
agrep | if NULL (the default unless keyword is used) and the character string to be matched consists of alphanumeric characters, whitespace or a dash only, approximate (fuzzy) matching via agrep is used unless the string has fewer than 5 characters; otherwise, it is taken to contain a regular expression to be matched via grep. If FALSE, approximate matching is not used. Otherwise, one can give a numeric or a list specifying the maximal distance for the approximate match, see argument max.distance in the documentation for agrep.

Details

Upon installation of a package, a pre-built help.search index is serialized as ‘hsearch.rds’ in the ‘Meta’ directory. These files are used to create the data base.

The arguments apropos and whatis play a role similar to the Unix commands with the same names.

If possible, the help data base is saved in memory or (if memory limits have been set: see mem.limits) to a file in the session temporary directory for use by subsequent calls in the session.

Note that currently the aliases in the matching help files are not displayed.

Value

The results are returned in a list object of class "hsearch", which has a print method for nicely formatting the results of the query. This mechanism is experimental, and may change in future versions of R.
The internal format of the class is undocumented and subject to change.

See Also

help; help.start for starting the hypertext (currently HTML) version of R's online documentation, which offers a similar search mechanism.

RSiteSearch to access an on-line search of R resources.

apropos uses regexps and has nice examples.

Examples

help.search("linear models")    # In case you forgot how to fit linear
                                # models
help.search("non-existent topic")
## Not run:
help.search("print")            # All help pages with topics or title
                                # matching 'print'
help.search(apropos = "print")  # The same

help.search(keyword = "hplot")  # All help pages documenting high-level
                                # plots.
file.show(file.path(R.home(), "doc", "KEYWORDS"))  # show all keywords

## Help pages with documented topics starting with 'try'.
help.search("\\btry", fields = "alias")
## Do not use '^' or '$' when matching aliases or keywords
## (unless all packages were installed using R 1.7 or newer).
## End(Not run)


Hypertext Documentation

Description

Start the hypertext (currently HTML) version of R's online documentation.

Usage

help.start(update = TRUE, gui = "irrelevant",
           browser = getOption("browser"))

Arguments

gui | just for compatibility with S-PLUS.
browser | the name of the program to be used as hypertext browser. It should be in the PATH, or a full path specified.
update | logical: should this attempt to update the indices to reflect the currently installed packages.

Details

The Windows file association mechanism is used to send the HTML file to a browser, launching one if necessary.

Unlike Unix systems, running help.start does not send all future help requests to the browser: use options(htmlhelp=TRUE) to set that.

Alternatively, a specific browser can be started if browser is specified, but help will still use the file association mechanism.

help.start and the Java-based search engine have been tested under Internet Explorer 6, Netscape 7.1, Opera 7.54, Mozilla 1.6/1.7 and MozillaFirefox 0.8/0.9/1.0. Users of IE6 under Windows XP SP2 will probably need to allow `active content' from the ‘information bar’ before the search engine can be used.

Note

There is a Java-based search facility available from the HTML page that help.start brings up. Should this not work, please consult the ‘R Installation and Administration’ manual which is linked from that page.

See Also

help() for on- and off-line help in ASCII/Editor or PostScript format.

browseURL for how the help file is displayed.

RSiteSearch to access an on-line search of R resources.

Examples

## Not run:
help.start()
help.start(browser="C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE")
help.start(browser="C:/Program Files/Netscape/Netscape/netscp.exe")
help.start(browser="C:/Program Files/Opera/Opera.exe")
help.start(browser="C:/Program Files/mozilla.org/Mozilla/mozilla.exe")
help.start(browser="C:/Program Files/Mozilla Firefox/firefox.exe")
## End(Not run)


Search Indices for Help Files

Description

Used to search the indices for help files, possibly under aliases.

Usage

index.search(topic, path, file="AnIndex", type = "help")

Arguments

topic | The keyword to be searched for in the indices.
path | The path(s) to the packages to be searched.
file | The index file to be searched. Normally ‘"AnIndex"’.
type | The type of file required.

Details

For each package in path, examine the file file in directory ‘type’, and look up the matching file stem for topic topic, if any.

Value

A character vector of matching files, as if they are in directory type of the corresponding package. In the special cases of type = "html", "R-ex" and "latex" the file extensions ".html", ".R" and ".tex" are added.

See Also

help, example


Install Add-on Packages from Sources

Description

To install packages into the default library tree (which is rooted at ‘$R_HOME/library’), do R CMD INSTALL pkgs.

To install into the library tree lib instead of the default one, use R CMD INSTALL -l lib pkgs.

Usage

R CMD INSTALL [options] [-l lib] pkgs

Arguments

pkgs | A space-separated list with the path names of the sources of the packages to be installed.
lib | the path name of the R library tree to install to.
options | a space-separated list of options through which in particular the process for building the help files can be controlled. Options should only be given once, and paths including spaces should be quoted. Use R CMD INSTALL --help for the current list of options.

Details

Windows Perl and the files for installing from source packages need to be installed.

Both lib and the elements of pkgs may be absolute or relative path names of directories. pkgs may also contain names of package archive files of the form ‘pkg_version.tar.gz’ as obtained from CRAN (these are then extracted in a temporary directory ‘R.INSTALL’ of the current directory).

Which forms of help are produced is controlled by the --docs option which takes values none or normal (text and HTML) or chm (the default, text, HTML and CHTML).

If the attempt to install the package fails, leftovers are removed. If the package was already installed, the old version is restored. This happens either if a command encounters an error or if the install is interrupted from the keyboard.

Use R CMD INSTALL --help for more usage information.

Packages using the methods package

Packages that require the methods package, and that use functions such as setMethod or setClass, should be installed either (preferably) using lazy-loading or by creating a binary image: use the flags LazyLoad and SaveImage in the ‘DESCRIPTION’ file to ensure this.

See Also

REMOVE and library for information on using several library trees; update.packages for automatic update of packages using the internet; the section on “Add-on packages” in “R Installation and Administration” and the chapter on “Creating R packages” in “Writing R Extensions” (see the ‘doc/manual’ subdirectory of the R source tree).


Find Installed Packages

Description

Find (or retrieve) details of all packages installed in the specified libraries.

Usage

installed.packages(lib.loc = NULL, priority = NULL,
                   noCache = FALSE, fields = NULL)

Arguments

lib.loc | character vector describing the location of R library trees to search through.
priority | character vector or NULL (default). If non-null, used to select packages; "high" is equivalent to c("base", "recommended"). To select all packages without an assigned priority use priority = "NA".
noCache | Do not use cached information.
fields | a character vector giving the fields to extract from each package's DESCRIPTION file in addition to the default ones, or NULL (default). Unavailable fields result in NA values.

Details

installed.packages scans the ‘DESCRIPTION’ files of each package found along lib.loc and returns a matrix of package names, library paths and version numbers.

Note: this works with package names, not bundle names, and for versioned installs with the name under which the package is installed, in the style mypkg_1.3-7.

The information found is cached (by library) for the R session and specified fields argument, and updated only if the top-level library directory has been altered, for example by installing or removing a package. If the cached information becomes confused, it can be refreshed by running installed.packages(noCache = TRUE).

Value

A matrix with one row per package, row names the package names and column names "Package", "LibPath", "Version", "Priority", "Bundle", "Contains", "Depends", "Suggests", "Imports" and "Built" (the R version the package was built under). Additional columns can be specified using the fields argument.

See Also

update.packages, INSTALL, REMOVE.

Examples

str(ip <- installed.packages(priority = "high"))
ip[, c(1,3:5)]
plic <- installed.packages(priority = "high", fields="License")
## what licenses are there:
table( plic[,"License"] )


Update HTML documentation files

Description

Functions to re-create the HTML documentation files to reflect all installed packages. make.packages.html creates the list of packages and make.search.html creates the database used by the Java search engine. link.html.help runs both, as well as fixup.libraries.URLs which attempts to fix up cross-library links.

Usage

link.html.help(verbose = FALSE, lib.loc = .libPaths())
make.packages.html(lib.loc = .libPaths())
make.search.html(lib.loc = .libPaths())

fixup.package.URLs(pkg, force = FALSE)
fixup.libraries.URLs(lib.loc = .libPaths())

Arguments

verbose | logical. If true, print out a message. For use to explain a delay when called from other functions.
lib.loc | character vector. List of libraries to be included.
pkg | character vector. The full path to a package.
force | logical. Should the links be fixed even if the stamp is present?

Details

Cross-library links do not work on this platform. fixup.package.URLs attempts to correct links in the named package to the doc directory (usually to icons) and to the base, datasets, utils, grDevices, graphics and stats packages, and then stamps a file ‘fixedHTMLlinks’ in the package directory. If that file is found, no correction is attempted unless force = TRUE or the R installation directory (recorded in the stamp) has been changed.

fixup.libraries.URLs calls fixup.package.URLs on all packages in current library trees except the standard one.

The functions will give a warning if the files are not writeable.

Value

make.packages.html and fixup.package.URLs return a logical showing if they suceeded.
The files ‘R_HOME\doc\html\packages.html’ and ‘R_HOME\doc\html\search\index.txt’ are (re-)created by make.packages.html and make.search.html respectively.

Note

You will need write permission in the ‘R_HOME\doc\html’ directory to use any of the first three functions, and in the appropriate library trees to use the last two.


Select a Suitable Encoding Name from a Locale Name

Description

This functions aims to find a suitable coding for the locale named, by default the current locale, and if it is a UTF-8 locale a suitable single-byte encoding.

Usage

localeToCharset(locale = Sys.getlocale("LC_CTYPE"))

Arguments

locale character string naming a locale.

Details

The operation differs by OS. A Windows locale is specified like "English_United Kingdom.1252". The final component gives the codepage, and this defines the encoding.

In the C locale the answer will be "ASCII".

Value

A character vector naming an encoding and possibly a fallback single-encoding, NA if unknown.

Note

The encoding names are those used by libiconv, and ought also to work with glibc but maybe not with commercial Unixen.

See Also

Sys.getlocale, iconv.

Examples

localeToCharset()


List Objects and their Structure

Description

ls.str and lsf.str are “variations” of ls applying str() to each matched name, see section ‘Value’.

Usage

ls.str(pos = 1, pattern, ...,  envir = as.environment(pos),
       mode = "any")

lsf.str(pos = 1, ..., envir = as.environment(pos))

## S3 method for class 'ls_str':
print(x, max.level = 1, give.attr = FALSE, ...)

Arguments

pos | integer indicating search path position.
pattern | a regular expression passed to ls. Only names matching pattern are considered.
max.level | maximal level of nesting which is applied for displaying nested structures, e.g., a list containing sub lists. Default 0: Display all nesting levels.
give.attr | logical; if TRUE (default), show attributes as sub structures.
envir | environment to use, see ls.
mode | character specifying the mode of objects to consider. Passed to exists and get.
x | an object of class "ls_str".
... | further arguments to pass. and lsf.str passes them to ls.str which passes them on to ls. The (non-exported) print method print.ls_str passes them to str.

Value

ls.str and lsf.str return an object of class "ls_str", basically the character vector of matching names (functions only for lsf.str), similarly to ls, with a print() method that calls str() on each object.

Author(s)

Martin Maechler

See Also

str, summary, args.

Examples

lsf.str()#- how do the functions look like which I am using?
ls.str(mode = "list") #- what are the structured objects I have defined?

## create a few objects
example(glm, echo = FALSE)
ll <- as.list(LETTERS)
print(ls.str(), max.level = 0)# don't show details

## which base functions have "file" in their name ?
lsf.str(pos = length(search()), pattern = "file")


Create a Socket Connection

Description

With server = FALSE attempts to open a client socket to the specified port and host. With server = TRUE listens on the specified port for a connection and then returns a server socket. It is a good idea to use on.exit to ensure that a socket is closed, as you only get 64 of them.

Usage

make.socket(host = "localhost", port, fail = TRUE, server = FALSE)

Arguments

host | name of remote host
port | port to connect to/listen on
fail | failure to connect is an error?
server | a server socket?

Value

An object of class "socket".

socket | socket number. This is for internal use
port | port number of the connection
host | name of remote computer

Warning

I don't know if the connecting host name returned when server = TRUE can be trusted. I suspect not.

Author(s)

Thomas Lumley

References

Adapted from Luke Tierney's code for XLISP-Stat, in turn based on code from Robbins and Robbins "Practical UNIX Programming"

See Also

close.socket, read.socket

Examples

daytime <- function(host = "localhost"){
    a <- make.socket(host, 13)
    on.exit(close.socket(a))
    read.socket(a)
}
## Offical time (UTC) from US Naval Observatory
## Not run: daytime("tick.usno.navy.mil")


Report on Memory Allocation

Description

memory.size reports the current or maximum memory allocation of the malloc function used in this version of R.

memory.limit reports or increases the limit in force on the total allocation.

Usage

memory.size(max = FALSE)

memory.limit(size = NA)

Arguments

max | logical. If true the maximum amount of memory obtained from the OS is reported, otherwise the amount currently in use.
size | numeric. If NA report the memory size, otherwise request a new limit, in Mb. Values of up to 4096 are allowed, but see Details.

Details

Command-line flag --max-mem-size sets the maximum value of obtainable memory (including a very small amount of housekeeping overhead). This cannot exceed 3Gb on Windows, and most versions of Windows are limited to 2Gb.

Memory limits can only be increased.

Value

Size in bytes.

See Also

Memory-limits for other limits.

The rw-FAQ for more details and references.

Examples

memory.size()
memory.size(TRUE)
round(memory.limit()/1048576.0, 2)


Menu Interaction Function

Description

menu presents the user with a menu of choices labelled from 1 to the number of choices. To exit without choosing an item one can select 0.

Usage

menu(choices, graphics = FALSE, title = "")

Arguments

choices | a character vector of choices
graphics | a logical indicating whether a graphics menu should be used if available.
title | a character string to be used as the title of the menu. NULL is also accepted.

Details

If graphics = TRUE and a windowing system is available (Windows, MacOS X or X11 via Tcl/Tk) a listbox widget is used, otherwise a text menu.

Ten or fewer items will be displayed in a single column, more in multiple columns if possible within the current display width.

No title is displayed if title is NULL or "".

Value

The number corresponding to the selected item, or 0 if no choice was made.

References

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

See Also

select.list, which is used to implement the graphical menu, and allows multiple selections.

Examples

## Not run:
switch(menu(c("List letters", "List LETTERS")) + 1,
       cat("Nothing done\n"), letters, LETTERS)
## End(Not run)


List Methods for S3 Generic Functions or Classes

Description

List all available methods for an S3 generic function, or all methods for a class.

Usage

methods(generic.function, class)

Arguments

generic.function | a generic function, or a character string naming a generic function.
class | a symbol or character string naming a class: only used if generic.function is not supplied.

Details

Function methods can be used to find out about the methods for a particular generic function or class. The functions listed are those which are named like methods and may not actually be methods (known exceptions are discarded in the code). Note that the listed methods may not be user-visible objects, but often help will be available for them.

If class is used, we check that a matching generic can be found for each user-visible object named. If generic.function is given, there is a warning if it appears not to be a generic function. (The check for being generic used can be fooled.)

Value

An object of class "MethodsFunction", a character vector of function names with an "info" attribute. There is a print method which marks with an asterisk any methods which are not visible: such functions can be examined by getS3method or getAnywhere.
The "info" attribute is a data frame, currently with a logical column, visible and a factor column from (indicating where the methods were found).

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. Functions can have both S3 and S4 methods, and function showMethods will list the S4 methods (possibly none).

The original methods function was written by Martin Maechler.

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

S3Methods, class, getS3method

Examples

methods(summary)
methods(class = "aov")
methods("[[")    # uses C-internal dispatching
methods("$")
methods("$<-")   # replacement function
methods("+")     # binary operator
methods("Math")  # group generic
methods("axis")  # looks like it has methods, but not generic
## Not run:
methods(print)   # over 100
## End(Not run)


Managing Repository Mirrors

Description

Functions helping to maintain CRAN, some of them may also be useful for administrators of other repository networks.

Usage

mirror2html(mirrors = NULL, file = "mirrors.html",
  head = "mirrors-head.html", foot = "mirrors-foot.html")
checkCRAN(method)

Arguments

mirrors | A data frame, by default the CRAN list of mirrors is used.
file | A connection object or a character string.
head | Name of optional header file.
foot | Name of optional footer file.
method | Download method, see download.file.

Details

mirror2html creates the HTML file for the CRAN list of mirrors and invisibly returns the HTML text.

checkCRAN performs a sanity checks on all CRAN mirrors.


Recursively Modify Elements of a List

Description

Modifies a possibly nested list recursively by changing a subset of elements at each level to match a second list.

Usage

modifyList(x, val)

Arguments

x | a named list, possibly empty.
val | a named list with components to replace corresponding components in x.

Value

A modified version of x, with the modifications determined as follows (here, list elements are identified by their names). Elements in val which are missing from x are added to x. For elements that are common to both but are not both lists themselves, the component in x is replaced by the one in val. For common elements that are both lists, x[[name]] is replaced by modifyList(x[[name]], val[[name]]).

Author(s)

Deepayan Sarkar Deepayan.Sarkar@R-project.org

Examples

foo <- list(a = 1, b = list(c = "a", d = FALSE))
bar <- modifyList(foo, list(e = 2, b = list(d = TRUE)))
str(foo)
str(bar)


Express File Paths in Canonical Form

Description

Convert file paths to canonical form for the platform, to display them in a user-understandable form.

Usage

normalizePath(path)

Arguments

path character vector of file paths.

Details

This converts relative paths to absolute paths, and converts short names to long names. It will always use backlashes as the path separator.

If the path is not a real path the result is undefined but will most likely be the corresponding input element.

Value

A character vector.

See Also

shortPathName

Examples

cat(normalizePath(c(R.home(), tempdir())), sep = "\n")


Report the Space Allocated for an Object

Description

Provides an estimate of the memory that is being used to store an R object.

Usage

object.size(x)

Arguments

x An R object.

Details

Exactly which parts of the memory allocation should be attributed to which object is not clear-cut. This function merely provides a rough indication: it should be reasonably accurate for atomic vectors, but does not detect if elements of a list are shared, for example. (Sharing amongst elements of a character vector is taken into account.)

The calculation is of the size of the object, and excludes the space needed to store its name in the symbol table.

Associated space (e.g. the enviromment of a function and what the pointer in a EXTPTRSXP points to) is not included in the calculation.

Object sizes are larger on 64-bit platforms than 32-bit ones, but will very likely be the same on different platforms with the same word length and pointer size.

Value

An estimate of the memory allocation attributable to the object, in bytes.

See Also

Memory-limits for the design limitations on object size.

Examples

object.size(letters)
object.size(ls)
## find the 10 largest objects in the base package
z <- sapply(ls("package:base"), function(x)
            object.size(get(x, envir = baseenv())))
as.matrix(rev(sort(z))[1:10])


Create a Skeleton for a New Source Package

Description

package.skeleton automates some of the setup for a new source package. It creates directories, saves functions and data to appropriate places, and creates skeleton help files and a ‘Read-and-delete-me’ file describing further steps in packaging.

Usage

package.skeleton(name = "anRpackage", list, environment = .GlobalEnv,
                 path = ".", force = FALSE, namespace = FALSE,
                 code_files = character())

Arguments

name | character string: the directory name for your package.
list | character vector naming the R objects to put in the package.
environment | if list is omitted and code_files is empty, the contents of this environment are packaged.
path | path to put the package directory in.
force | If FALSE will not overwrite an existing directory.
namespace | a logical indicating whether to add a name space for the package.
code_files | a character vector with the paths to R code files to build the package around.

Details

The package sources are placed in subdirectory name of path.

This tries to create filenames valid for all OSes known to run R. Invalid characters are replaced by _, invalid names are preceded by zz, and finally the converted names are made unique by make.unique(sep = "_"). This can be done for code and help files but not data files (which are looked for by name). Also, the code and help files should have names starting with an ASCII letter or digit, and this is checked and if necessary z prepended.

If code_files are given, these are copied over to the package code directory (so that non-function code objects are not converted to data sets), and the corresponding help files are generated.

When you are done, delete the ‘Read-and-delete-me’ file, as it should not be distributed.

Value

used for its side-effects.

References

Read the Writing R Extensions manual for more details.

Once you have created a source package you need to install it: see the R Installation and Administration manual, INSTALL and install.packages.

See Also

prompt

Examples

## two functions and two "data sets" :
f <- function(x,y) x+y
g <- function(x,y) x-y
d <- data.frame(a=1, b=2)
e <- rnorm(1000)

package.skeleton(list=c("f","g","d","e"), name="mypkg")


Package Description

Description

Parses and returns the ‘DESCRIPTION’ file of a package.

Usage

packageDescription(pkg, lib.loc = NULL, fields = NULL, drop = TRUE,
                   encoding = "")

Arguments

pkg | a character string with the package name.
lib.loc | a character vector of directory 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.
fields | a character vector giving the tags of fields to return (if other fields occur in the file they are ignored).
drop | If TRUE and the length of fields is 1, then a single character string with the value of the respective field is returned instead of an object of class "packageDescription".
encoding | If there is an Encoding field, to what encoding should re-encodong be attempted? If NA, no re-encoding. The other values are as used by iconv, so the default "" indicates the encoding of the current locale.

Details

A package will not be ‘found’ unless it has a ‘DESCRIPTION’ file which contains a valid Version field. Different warnings are given when no package directory is found and when there is a suitable directory but no valid ‘DESCRIPTION’ file.

Value

If a ‘DESCRIPTION’ file for the given package is found and can successfully be read, packageDescription returns an object of class "packageDescription", which is a named list with the values of the (given) fields as elements and the tags as names, unless drop = TRUE.
If parsing the ‘DESCRIPTION’ file was not successful, it returns a named list of NAs with the field tags as names if fields is not null, and NA otherwise.

See Also

read.dcf

Examples

packageDescription("stats")
packageDescription("stats", fields = c("Package", "Version"))

packageDescription("stats", fields = "Version")
packageDescription("stats", fields = "Version", drop = FALSE)


Package Management Tools

Description

Summarize information about installed packages and packages available at various repositories, and automatically upgrade outdated packages.

Usage

packageStatus(lib.loc = NULL, repositories = NULL, method,
              type = getOption("pkgType"))

## S3 method for class 'packageStatus':
summary(object, ...)

## S3 method for class 'packageStatus':
update(object, lib.loc = levels(object$inst$LibPath),
       repositories = levels(object$avail$Repository), ...)

## S3 method for class 'packageStatus':
upgrade(object, ask = TRUE, ...)

Arguments

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.
repositories | a character vector of URLs describing the location of R package repositories on the Internet or on the local machine.
method | Download method, see download.file.
type | type of package distribution: see install.packages.
object | an object of class "packageStatus" as returned by packageStatus.
ask | if TRUE, the user is prompted which packages should be upgraded and which not.
... | currently not used.

Details

The URLs in repositories should be full paths to the appropriate contrib sections of the repositories. The default is contrib.url(getOption("repos")).

There are print and summary methods for the "packageStatus" objects: the print method gives a brief tabular summary and the summary method prints the results.

The update method updates the "packageStatus" object. The upgrade method is similar to update.packages: it offers to install the current versions of those packages which are not currently up-to-date.

Value

An object of class "packageStatus". This is a list with two components

inst | a data frame with columns as the matrix returned by installed.packages plus "Status", a factor with levels c("ok", "upgrade"). Only the newest version of each package is reported, in the first repository in which it appears.
avail | a data frame with columns as the matrix returned by available.packages plus "Status", a factor with levels c("installed", "not installed", "unavailable")..

See Also

installed.packages, available.packages

Examples

## Not run:
x <- packageStatus()
print(x)
summary(x)
upgrade(x)
x <- update(x)
print(x)
## End(Not run)


Invoke a Pager on an R Object

Description

Displays a representation of the object named by x in a pager via file.show.

Usage

page(x, method = c("dput", "print"), ...)

Arguments

x | An R object, or a character string naming an object.
method | The default method is to dump the object via dput. An alternative is to use print and capture the output to be shown in the pager.
... | additional arguments for dput, print or file.show (such as title).

Details

If x is a length-one character vector, it is used as the name of an object to look up in the environment from which page is called. All other objects are displayed directly.

A default value of title is passed to file.show if one is not supplied in ....

See Also

file.show, edit, fix.

To go to a new page when graphing, see frame.

Examples

## Not run:
## four ways to look at the code of 'page'
page(page)             # as an object
page("page")           # a character string
v <- "page"; page(v)   # a length-one character vector
page(utils::page)      # a call
## End(Not run)


Person Names and Contact Information

Description

A class and utility methods for holding information about persons like name and email address.

Usage

person(first = "", last = "", middle = "", email = "")
personList(...)
as.person(x)
as.personList(x)

## S3 method for class 'person':
as.character(x, ...)
## S3 method for class 'personList':
as.character(x, ...)

## S3 method for class 'person':
toBibtex(object, ...)
## S3 method for class 'personList':
toBibtex(object, ...)

Arguments

first | character string, first name
middle | character string, middle name(s)
last | character string, last name
email | character string, email address
... | for personList an arbitrary number of person objects
x | a character string or an object of class person or personList
object | an object of class person or personList

Examples

## create a person object directly
p1 <- person("Karl", "Pearson", email = "pearson@stats.heaven")
p1

## convert a string
p2 <- as.person("Ronald Aylmer Fisher")
p2

## create one object holding both
p <- personList(p1, p2)
ps <- as.character(p)
ps
as.personList(ps)

## convert to BibTeX author field
toBibtex(p)


Utilities for Building and Checking Add-on Packages

Description

Utilities for checking whether the sources of an R add-on package work correctly, and for building a source or binary package from them.

Usage

R CMD build [options] pkgdirs
R CMD check [options] pkgdirs

Arguments

pkgdirs | a list of names of directories with sources of R add-on packages.
options | further options to control the processing, or for obtaining information about usage and version of the utility.

Details

R CMD check checks R add-on packages from their sources, performing a wide variety of diagnostic checks.

R CMD build builds R source or binary packages from their sources. It will create index files in the sources if necessary, so it is often helpful to run build before check.

Use R CMD foo --help to obtain usage information on utility foo.

Several of the options to build --binary are passed to INSTALL so consult its help for the details.

Note

These may not work correctly under Windows 95/98/ME because of problems Perl has launching programs on those limited OSes.

They make use of a temporary directory specified by the enironment variable TMPDIR and defaulting to c:/TEMP. Do ensure that if set forward slashes are used.

See Also

The sections on “Checking and building packages” and “Processing Rd format” in “Writing R Extensions” (see the Manuals sub-menu of the Help menu on the console).

INSTALL is called by build --binary.


Produce Prototype of an R Documentation File

Description

Facilitate the constructing of files documenting R objects.

Usage

prompt(object, filename = NULL, name = NULL, ...)

## Default S3 method:
prompt(object, filename = NULL, name = NULL,
       force.function = FALSE, ...)

## S3 method for class 'data.frame':
prompt(object, filename = NULL, name = NULL, ...)

Arguments

object | an R object, typically a function for the default method.
filename | usually, a connection or a character string giving the name of the file to which the documentation shell should be written. The default corresponds to a file whose name is name followed by ".Rd". Can also be NA (see below).
name | a character string specifying the name of the object.
force.function | a logical. If TRUE, treat object as function in any case.
... | further arguments passed to or from other methods.

Details

Unless filename is NA, a documentation shell for object is written to the file specified by filename, and a message about this is given. For function objects, this shell contains the proper function and argument names. R documentation files thus created still need to be edited and moved into the ‘man’ subdirectory of the package containing the object to be documented.

If filename is NA, a list-style representation of the documentation shell is created and returned. Writing the shell to a file amounts to cat(unlist(x), file = filename, sep = "\n"), where x is the list-style representation.

When prompt is used in for loops or scripts, the explicit name specification will be useful.

Value

If filename is NA, a list-style representation of the documentation shell. Otherwise, the name of the file written to is returned invisibly.

Warning

The default filename may not be a valid filename under limited file systems (e.g. those on Windows).

Currently, calling prompt on a non-function object assumes that the object is in fact a data set and hence documents it as such. This may change in future versions of R. Use promptData to create documentation skeletons for data sets.

Note

The documentation file produced by prompt.data.frame does not have the same format as many of the data frame documentation files in the base package. We are trying to settle on a preferred format for the documentation.

Author(s)

Douglas Bates for prompt.data.frame

References

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

See Also

promptData, help and the chapter on “Writing R documentation” in “Writing R Extensions” (see the ‘doc/manual’ subdirectory of the R source tree).

For creation of many help pages (for a package), see package.skeleton.

To prompt the user for input, see readline.

Examples

require(graphics)
prompt(plot.default)
prompt(interactive, force.function = TRUE)
unlink("plot.default.Rd")
unlink("interactive.Rd")

prompt(women) # data.frame
unlink("women.Rd")

prompt(sunspots) # non-data.frame data
unlink("sunspots.Rd")


Generate a Shell for Documentation of Data Sets

Description

Generates a shell of documentation for a data set.

Usage

promptData(object, filename = NULL, name = NULL)

Arguments

object | an R object to be documented as a data set.
filename | usually, a connection or a character string giving the name of the file to which the documentation shell should be written. The default corresponds to a file whose name is name followed by ".Rd". Can also be NA (see below).
name | a character string specifying the name of the object.

Details

Unless filename is NA, a documentation shell for object is written to the file specified by filename, and a message about this is given.

If filename is NA, a list-style representation of the documentation shell is created and returned. Writing the shell to a file amounts to cat(unlist(x), file = filename, sep = "\n"), where x is the list-style representation.

Currently, only data frames are handled explicitly by the code.

Value

If filename is NA, a list-style representation of the documentation shell. Otherwise, the name of the file written to is returned invisibly.

Warning

This function is still experimental. Both interface and value might change in future versions. In particular, it may be preferable to use a character string naming the data set and optionally a specification of where to look for it instead of using object/name as we currently do. This would be different from prompt, but consistent with other prompt-style functions in package methods, and also allow prompting for data set documentation without explicitly having to load the data set.

See Also

prompt

Examples

promptData(sunspots)
unlink("sunspots.Rd")


Generate a Shell for Documentation of a Package

Description

Generates a shell of documentation for an installed or source package.

Usage

promptPackage(package, lib.loc = NULL, filename = NULL,
              name = NULL, final = FALSE)

Arguments

package | the name of an installed or source package to be documented.
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. For a source package this should specify the parent directory of the package's sources.
filename | usually, a connection or a character string giving the name of the file to which the documentation shell should be written. The default corresponds to a file whose name is name followed by ".Rd". Can also be NA (see below).
name | a character string specifying the name of the help topic, typically of the form <pkg>-package.
final | a logical value indicating whether to attempt to create a usable version of the help topic, rather than just a shell.

Details

Unless filename is NA, a documentation shell for package is written to the file specified by filename, and a message about this is given.

If filename is NA, a list-style representation of the documentation shell is created and returned. Writing the shell to a file amounts to cat(unlist(x), file = filename, sep = "\n"), where x is the list-style representation.

If final is TRUE, the generated documentation will not include the place-holder slots for manual editing, it will be usable as-is. In most cases a manually edited file is preferable (but final = TRUE is certainly less work).

Value

If filename is NA, a list-style representation of the documentation shell. Otherwise, the name of the file written to is returned invisibly.

See Also

prompt

Examples

filename <- tempfile()
promptPackage("utils", file=filename)
file.show(filename)
unlink(filename)


R for Windows Configuration

Description

The file ‘Rconsole’ configures the R GUI console in this Windows port. The loadRconsole function loads a new configuration.

The file ‘Rdevga’ configures the graphics devices windows, win.graph, win.metafile and win.print, as well as the bitmap devices bmp, jpeg and png (which use windows internally).

Usage

  loadRconsole(file)

Arguments

file The file from which to load a new ‘Rconsole’ configuration. By default a file dialog is used to select a file.

Details

There are system copies of these files in ‘R_HOME\etc’. Users can have personal copies of the files: these are looked for in the location given by the environment variable R_USER. The system files are read only if a corresponding personal file is not found.

If the environment variable R_USER is not set, the R system sets it to HOME if that is set (stripping any trailing slash), otherwise to the Windows “personal” directory, otherwise to {HOMEDRIVE}{HOMEPATH} if HOMEDRIVE and HOMEDRIVE are both set otherwise to the working directory. This is as described in the file ‘rw-FAQ’.

Value

Each of the files contains details in its comments of how to set the values.
At the time of writing ‘Rdevga’ configured the mapping of font numbers to fonts, and ‘Rconsole’ configured the appearance (single or multiple document interface, toolbar, statusbar on MDI), size, font and colours of the GUI console, and whether resizing the console sets options("width").
The file ‘Rconsole’ also configures the internal pager. This shares the font and colours of the console, but can be sized separately.
‘Rconsole’ can also set the initial positions of the console and the graphics device, as well as the size and position of the MDI workspace in MDI mode.
loadRconsole is called for its side effect of loading new defaults. It returns no useful value.

Chinese/Japanese/Korean

Users of these languages will need to select a suitable font for the console (perhaps FixedSys or MS Mincho) and for the graphics device (Arial can be replaced by Arial Unicode MS).

Which fonts are available depends on the version of Windows.

Note

The GUI preferences item on the Edit menu brings up an dialog box which can be used to edit the console settings, and to save them to a file.

Author(s)

Guido Masarotto and R-core members

See Also

windows

Examples

ruser <- Sys.getenv("R_USER")
cat("\n\nLocation for personal configuration files is\n   R_USER = ",
    ruser, "\n\n", sep="")
## see if there are personal configuration files
sapply(c("Rconsole", "Rdevga"), function(x) file.exists(file.path(ruser, x)))

## show the configuration files used
showConfig <- function(file)
{
    ruser <- Sys.getenv("R_USER")
    path <- file.path(ruser, file)
    if(!file.exists(path)) path <- file.path(R.home(), "etc", file)
    file.show(path, header=path)
}
showConfig("Rconsole")


Data Input from Spreadsheet

Description

Reads a file in Data Interchange Format (DIF) and creates a data frame from it. DIF is a format for data matrices such as single spreadsheets.

Usage

read.DIF(file, header = FALSE,
           dec = ".", row.names, col.names,
           as.is = !stringsAsFactors,
           na.strings = "NA", colClasses = NA, nrows = -1,
           skip = 0, check.names = TRUE,
           blank.lines.skip = TRUE,
           stringsAsFactors = default.stringsAsFactors())

Arguments

file | the name of the file which the data are to be read from, or a connection, or a complete URL. The name "clipboard" may also be used on Windows, in which case read.DIF("clipboard") will look for a DIF format entry in the Windows clipboard.
header | a logical value indicating whether the spreadsheet 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 only character values and the top left cell is empty.
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.DIF 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.
blank.lines.skip | logical: if TRUE blank lines in the input are ignored.
stringsAsFactors | logical: should character vectors be converted to factors?

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.

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.

References

The DIF format specification can be found by searching on http://www.wotsit.org/; the optional header fields are ignored. See also http://en.wikipedia.org/wiki/Data_Interchange_Format.

The term is likely to lead to confusion: Windows will have a ‘Windows Data Interchange Format (DIF) data format’ as part of its WinFX system, which may or may not be compatible.

See Also

The R Data Import/Export manual.

scan, type.convert, read.fwf for reading fixed width formatted input; read.table; data.frame.


Read fixed-format data

Description

Read fixed-format data files using Fortran-style format specifications.

Usage

read.fortran(file, format, ..., as.is = TRUE, colClasses = NA)

Arguments

file | File or connection to read from
format | Character vector or list of vectors. See Details below.
... | Other arguments for read.table
as.is | Keep characters as characters?
colClasses | Variable classes to override defaults. See read.table for details.

Details

The format for a field is of one of the following forms: rFl.d, rDl.d, rXl, rAl, rIl, where l is the number of columns, d is the number of decimal places, and r is the number of repeats. F and D are numeric formats, A is character, I is integer, and X indicates columns to be skipped. The repeat code r and decimal place code d are always optional. The length code l is required except for X formats when r is present.

For a single-line record, format should be a character vector. For a multiline record it should be a list with a character vector for each line.

Skipped (X) columns are not passed to read.table, so colClasses, col.names, and similar arguments passed to read.table should not reference these columns.

Value

A data frame

See Also

read.fwf, read.csv

Examples

ff <- tempfile()
cat(file=ff, "123456", "987654", sep="\n")
read.fortran(ff, c("F2.1","F2.0","I2"))
read.fortran(ff, c("2F1.0","2X","2A1"))
unlink(ff)
cat(file=ff, "123456AB", "987654CD", sep="\n")
read.fortran(ff, list(c("2F3.1","A2"), c("3I2","2X")))
unlink(ff)


Read Fixed Width Format Files

Description

Read a “table” of fixed width formatted data into a data.frame.

Usage

read.fwf(file, widths, header = FALSE, sep = "\t", as.is = FALSE,
         skip = 0, row.names, col.names, n = -1,
         buffersize = 2000, ...)

Arguments

file | the name of the file which the data are to be read from. Alternatively, file can be a connection, which will be opened if necessary, and if so closed at the end of the function call.
widths | integer vector, giving the widths of the fixed-width fields (of one line), or list of integer vectors giving widths for multiline records.
header | a logical value indicating whether the file contains the names of the variables as its first line. If present, the names must be delimited by sep.
sep | character; the separator used internally; should be a character that does not occur in the file (except in the header).
as.is | see read.table.
skip | number of initial lines to skip; see read.table.
row.names | see read.table.
col.names | see read.table.
n | the maximum number of records (lines) to be read, defaulting to no limit.
buffersize | Maximum number of lines to read at one time
... | further arguments to be passed to read.table. Useful further arguments include na.strings, colClasses and strip.white.

Details

Multiline records are concatenated to a single line before processing. Fields that are of zero-width or are wholly beyond the end of the line in file are replaced by NA.

Negative-width fields are used to indicate columns to be skipped, eg -5 to skip 5 columns. These fields are not seen by read.table and so should not be included in a col.names or colClasses argument (nor in the header line, if present).

Reducing the buffersize argument may reduce memory use when reading large files with long lines. Increasing buffersize may result in faster processing when enough memory is available.

Value

A data.frame as produced by read.table which is called internally.

Author(s)

Brian Ripley for R version: original Perl by Kurt Hornik.

See Also

scan and read.table.

Examples

ff <- tempfile()
cat(file=ff, "123456", "987654", sep="\n")
read.fwf(ff, width=c(1,2,3))    #> 1 23 456 \ 9 87 654
read.fwf(ff, width=c(1,-2,3))   #> 1 456 \ 9 654
unlink(ff)
cat(file=ff, "123", "987654", sep="\n")
read.fwf(ff, width=c(1,0, 2,3))    #> 1 NA 23 NA \ 9 NA 87 654
unlink(ff)
cat(file=ff, "123456", "987654", sep="\n")
read.fwf(ff, width=list(c(1,0, 2,3), c(2,2,2)))    #> 1 NA 23 456 98 76 54
unlink(ff)


Read from or Write to a Socket

Description

read.socket reads a string from the specified socket, write.socket writes to the specified socket. There is very little error checking done by either.

Usage

read.socket(socket, maxlen = 256, loop = FALSE)
write.socket(socket, string)

Arguments

socket | a socket object
maxlen | maximum length of string to read
loop | wait for ever if there is nothing to read?
string | string to write to socket

Value

read.socket returns the string read.

Author(s)

Thomas Lumley

See Also

close.socket, make.socket

Examples

finger <- function(user, host = "localhost", port = 79, print = TRUE)
{
    if (!is.character(user))
        stop("user name must be a string")
    user <- paste(user,"\r\n")
    socket <- make.socket(host, port)
    on.exit(close.socket(socket))
    write.socket(socket, user)
    output <- character(0)
    repeat{
        ss <- read.socket(socket)
        if (ss == "") break
        output <- paste(output, ss)
    }
    close.socket(socket)
    if (print) cat(output)
    invisible(output)
}
## Not run:
finger("root")  ## only works if your site provides a finger daemon
## End(Not run)


Read R's NEWS file or a Similar One

Description

Read R's NEWS file or a similarly formatted one. This is an experimental feature, new in R 2.4.0 and may change in several ways.

Usage

readNEWS(file = file.path(R.home(), "NEWS"), trace = FALSE,
         chop = c("first", "1", "par1", "keepAll"))

Arguments

file | the name of the file which the data are to be read from. Alternatively, file can be a connection, which will be opened if necessary, and can also be a complete URL. For more details, see the file argument of read.table.
trace | logical indicating if the recursive reading should be traced, i.e., print what it is doing.
chop | a character string specifying how the news entries should be “chopped”; chop = "keepAll" saves the full entries.

Value

An (S3) object of class "newsTree"; effectively a list of lists which is a tree of NEWS entries.
Note that this is still experimental and may change in the future.

Examples

NEWStr  <- readNEWS(trace = TRUE)# chop = "first" ( = "first non-empty")
## keep the full NEWS entry text i.e. "no chopping":
NEWStrA <- readNEWS(chop = "keepAll")
object.size(NEWStr)
object.size(NEWStrA) ## (no chopping) ==> about double the size

str(NEWStr, max = 3)

str(NEWStr[[c("2.3", "2.3.1")]], max=2, vec.len=1)

NEWStr [[c("2.3", "2.3.1", "NEW FEATURES")]]
NEWStrA[[c("2.4", "2.4.0", "NEW FEATURES")]]


Browsing after an Error

Description

This function allows the user to browse directly on any of the currently active function calls, and is suitable as an error option. The expression options(error=recover) will make this the error option.

Usage

recover()

Details

When called, recover prints the list of current calls, and prompts the user to select one of them. The standard R browser is then invoked from the corresponding environment; the user can type ordinary S language expressions to be evaluated in that environment.

When finished browsing in this call, type c to return to recover from the browser. Type another frame number to browse some more, or type 0 to exit recover.

The use of recover largely supersedes dump.frames as an error option, unless you really want to wait to look at the error. If recover is called in non-interactive mode, it behaves like dump.frames. For computations involving large amounts of data, recover has the advantage that it does not need to copy out all the environments in order to browse in them. If you do decide to quit interactive debugging, call dump.frames directly while browsing in any frame (see the examples).

WARNING: The special Q command to go directly from the browser to the prompt level of the evaluator currently interacts with recover to effectively turn off the error option for the next error (on subsequent errors, recover will be called normally).

Value

Nothing useful is returned. However, you can invoke recover directly from a function, rather than through the error option shown in the examples. In this case, execution continues after you type 0 to exit recover.

Compatibility Note

The R recover function can be used in the same way as the S-Plus function of the same name; therefore, the error option shown is a compatible way to specify the error action. However, the actual functions are essentially unrelated and interact quite differently with the user. The navigating commands up and down do not exist in the R version; instead, exit the browser and select another frame.

References

John M. Chambers (1998). Programming with Data; Springer.
See the compatibility note above, however.

See Also

browser for details about the interactive computations; options for setting the error option; dump.frames to save the current environments for later debugging.

Examples

## Not run:

options(error = recover) # setting the error option

### Example of interaction

> myFit <- lm(y ~ x, data = xy, weights = w)
Error in lm.wfit(x, y, w, offset = offset, ...) :
        missing or negative weights not allowed

Enter a frame number, or 0 to exit
1:lm(y ~ x, data = xy, weights = w)
2:lm.wfit(x, y, w, offset = offset, ...)
Selection: 2
Called from: eval(expr, envir, enclos)
Browse[1]> objects() # all the objects in this frame
[1] "method" "n"      "ny"     "offset" "tol"    "w"
[7] "x"      "y"
Browse[1]> w
[1] -0.5013844  1.3112515  0.2939348 -0.8983705 -0.1538642
[6] -0.9772989  0.7888790 -0.1919154 -0.3026882
Browse[1]> dump.frames() # save for offline debugging
Browse[1]> c # exit the browser

Enter a frame number, or 0 to exit
1:lm(y ~ x, data = xy, weights = w)
2:lm.wfit(x, y, w, offset = offset, ...)
Selection: 0 # exit recover
>

## End(Not run)


Remove Add-on Packages

Description

Use R CMD REMOVE pkgs to remove the packages in pkgs from the default library tree (which is rooted at ‘$R_HOME/library’).

To remove from the library tree lib instead of the default one, use R CMD REMOVE -l lib pkgs.

Usage

R CMD REMOVE [-l lib] pkgs

Arguments

pkgs | a list with the names of the packages to be removed.
lib | the path name of the R library tree to remove from. May be absolute or relative.

Details

Windows Perl and the files for installing from source packages need to be installed.

See Also

INSTALL, remove.packages


Remove Installed Packages

Description

Removes installed packages/bundles and updates index information as necessary.

Usage

remove.packages(pkgs, lib, version)

Arguments

pkgs | a character vector with the names of the package(s) or bundle(s) to be removed.
lib | a character vector giving the library directories to remove the packages from. If missing, defaults to the first element in .libPaths().
version | A character vector specifying version(s) with versioned installs of the package(s) to remove. If none is provided, the system will remove an unversioned install of the package if one is found, otherwise the latest versioned install.

Details

If an element of pkgs matches a bundle name, all the packages in the bundle will be removed. This takes precedence over matching a package name.

pkgs and version will be recycled if necessary to the length of the longer one.

See Also

install.packages for installing packages.


Enable Profiling of R's Execution

Description

Enable or disable profiling of the execution of R expressions.

Usage

Rprof(filename = "Rprof.out", append = FALSE, interval = 0.02,
       memory.profiling=FALSE)

Arguments

filename | The file to be used for recording the profiling results. Set to NULL or "" to disable profiling.
append | logical: should the file be over-written or appended to?
interval | real: time interval between samples.
memory.profiling | logical: write memory use information to the file?

Details

Enabling profiling automatically disables any existing profiling to another or the same file.

Profiling works by writing out the call stack every interval seconds, to the file specified. Either the summaryRprof function or the Perl script R CMD Rprof can be used to process the output file to produce a summary of the usage; use R CMD Rprof --help for usage information.

Exactly what the time interval measures is subtle: it is time that the R process is running and executing an R command. It is not however just CPU time, for if readline() is waiting for input, that counts (on Windows, but not on Unix).

Note that the timing interval cannot be too small, for the time spent in each profiling step is added to the interval. What is feasible is machine-dependent, but 10ms seems as small as advisable on a 1GHz machine.

Note

Using R CMD Rprof needs Windows Perl to be installed.

See Also

The chapter on “Tidying and profiling R code” in “Writing R Extensions” (see the ‘doc/manual’ subdirectory of the R source tree).

summaryRprof

tracemem, Rprofmem for other ways to track memory use.

Examples

## Not run:
Rprof()
## some code to be profiled
Rprof(NULL)
## some code NOT to be profiled
Rprof(append=TRUE)
## some code to be profiled
Rprof(NULL)
...
## Now post-process the output as described in Details
## End(Not run)


Enable Profiling of R's Memory Use

Description

Enable or disable reporting of memory allocation in R.

Usage

Rprofmem(filename = "Rprofmem.out", append = FALSE, threshold = 0)

Arguments

filename | The file to be used for recording the memory allocations. Set to NULL or "" to disable reporting.
append | logical: should the file be over-written or appended to?
threshold | numeric: allocations on R's "large vector" heap larger than this number of bytes will be reported.

Details

Enabling profiling automatically disables any existing profiling to another or the same file.

Profiling writes the call stack to the specified file every time malloc is called to allocate a large vector object or to allocate a page of memory for small objects. The size of a page of memory and the size above which malloc is used for vectors are compile-time constants, by default 2000 and 128 bytes respectively.

The profiler tracks allocations, some of which will be to previously used memory and will not increase the total memory use of R.

Value

None

Note

The memory profiler slows down R even when not in use, and so is a compile-time option. The memory profiler can be used at the same time as other R and C profilers.

See Also

The R sampling profiler, Rprof also collects memory information.

tracemem traces duplications of specific objects.

The "Writing R Extensions" manual section on "Tidying and profiling R code"

Examples

## Not run:
## not supported unless R is compiled to support it.
Rprofmem("Rprofmem.out", threshold=1000)
example(glm)
Rprofmem(NULL)
noquote(readLines("Rprofmem.out", n=5))
## End(Not run)


Search for Key Words or Phrases in the R-help Mailing List Archives or Documentation

Description

Search for key words or phrases in the R-help mailing list archives, or R manuals and help pages, using the search engine at http://search.r-project.org and view them in a web browser.

Usage

RSiteSearch(string,
            restrict = c("Rhelp02a", "functions", "docs"),
            format = "normal", sortby = "score",
            matchesPerPage = 20)

Arguments

string | word(s) or phrase to search. If the words are to be searched as one entity, enclose all words in braces (see example).
restrict | character: What areas to search in: Rhelp02a for R-help mailing list archive since 2002, Rhelp01 for mailing list archive before 2002, docs for R manuals, functions for help pages. Use c() to specify more than one.
format | normal or short (no excerpts).
sortby | How to sort the search results (score, date:late for sorting by date with latest results first, date:early for earliest first, subject for subject in alphabetical order, subject:descending for reverse alphabetical order, from or from:descending for sender (when applicable), size or size:descending for size.)
matchesPerPage | How many items to show per page.

Details

This function is designed to work with the search site at http://search.r-project.org, and depends on that site continuing to be made available (thanks to Jonathan Baron and the School of Arts and Sciences of the University of Pennslyvania).

Unique partial matches will work for all arguments. Each new browser window will stay open unless you close it.

Value

(Invisibly) the complete URL passed to the browser, including the query string.

Author(s)

Andy Liaw and Jonathan Baron

See Also

help.search, help.start for local searches.

browseURL for how the help file is displayed.

Examples

## Not run:
 # need Internet connection
RSiteSearch("{logistic regression}") # matches exact phrase
RSiteSearch("Baron Liaw", res = "Rhelp02")
## End(Not run)


R Driver for Stangle

Description

A driver for Stangle that extracts R code chunks.

Usage

Rtangle()
RtangleSetup(file, syntax, output = NULL, annotate = TRUE,
             split = FALSE, prefix = TRUE, quiet = FALSE)

Arguments

file | Name of Sweave source file.
syntax | An object of class SweaveSyntax.
output | Name of output file, default is to remove extension ‘.nw’, ‘.Rnw’ or ‘.Snw’ and to add extension ‘.R’. Any directory names in file are also removed such that the output is created in the current working directory.
annotate | By default, code chunks are seperated by comment lines specifying the names and numbers of the code chunks. If FALSE, only the code chunks without any decorating comments are extracted.
split | Split output in single files per code chunk?
prefix | If split = TRUE, prefix the chunk labels by the basename of the input file to get output file names?
quiet | If TRUE all progress messages are suppressed.

Author(s)

Friedrich Leisch

References

Friedrich Leisch: Sweave User Manual, 2002
http://www.ci.tuwien.ac.at/~leisch/Sweave

See Also

Sweave, RweaveLatex


R/LaTeX Driver for Sweave

Description

A driver for Sweave that translates R code chunks in LaTeX files.

Usage

RweaveLatex()

RweaveLatexSetup(file, syntax, output = NULL, quiet = FALSE,
                 debug = FALSE, echo = TRUE, eval  =  TRUE,
                 split = FALSE, stylepath = TRUE,
                 pdf = TRUE, eps = TRUE)

Arguments

file | Name of Sweave source file.
syntax | An object of class SweaveSyntax.
output | Name of output file, default is to remove extension ‘.nw’, ‘.Rnw’ or ‘.Snw’ and to add extension ‘.tex’. Any directory names in file are also removed such that the output is created in the current working directory.
quiet | If TRUE all progress messages are suppressed.
debug | If TRUE, input and output of all code chunks is copied to the console.
stylepath | If TRUE, a hard path to the file ‘Sweave.sty’ installed with this package is set, if FALSE, only \usepackage{Sweave} is written. The hard path makes the TeX file less portable, but avoids the problem of installing the current version of ‘Sweave.sty’ to some place in your TeX input path. The argument is ignored if a \usepackage{Sweave} is already present in the Sweave source file.
echo | set default for option echo, see details below.
eval | set default for option eval, see details below.
split | set default for option split, see details below.
pdf | set default for option pdf, see details below.
eps | set default for option eps, see details below.

Supported Options

RweaveLatex supports the following options for code chunks (the values in parentheses show the default values):

echo:
logical (TRUE). Include S code in the output file?
eval:
logical (TRUE). If FALSE, the code chunk is not evaluated, and hence no text or graphical output produced.
results:
character string (verbatim). If verbatim, the output of S commands is included in the verbatim-like Soutput environment. If tex, the output is taken to be already proper latex markup and included as is. If hide then all output is completely suppressed (but the code executed during the weave).
print:
logical (FALSE) If TRUE, each expression in the code chunk is wrapped into a print() statement before evaluation, such that the values of all expressions become visible.
term:
logical (TRUE). If TRUE, visibility of values emulates an interactive R session: values of assignments are not printed, values of single objects are printed. If FALSE, output comes only from explicit print or cat statements.
split:
logical (FALSE). If TRUE, text output is written to separate files for each code chunk.
strip.white:
character string (false). If true, blank lines at the beginning and end of output are removed. If all, then all blank lines are removed from the output.
prefix:
logical (TRUE). If TRUE generated filenames of figures and output have a common prefix.
prefix.string:
a character string, default is the name of the ‘.Snw’ source file.
include:
logical (TRUE), indicating whether input statements for text output and includegraphics statements for figures should be auto-generated. Use include = FALSE if the output should appear in a different place than the code chunk (by placing the input line manually).
fig:
logical (FALSE), indicating whether the code chunk produces graphical output. Note that only one figure per code chunk can be processed this way.
eps:
logical (TRUE), indicating whether EPS figures shall be generated. Ignored if fig = FALSE.
pdf:
logical (TRUE), indicating whether PDF figures shall be generated. Ignored if fig = FALSE.
width:
numeric (6), width of figures in inch.
height:
numeric (6), height of figures in inch.

Author(s)

Friedrich Leisch

References

Friedrich Leisch: Sweave User Manual, 2002
http://www.ci.tuwien.ac.at/~leisch/Sweave

See Also

Sweave, Rtangle


Load or Save or Display the Commands History

Description

Load or save or display the commands history.

Usage

loadhistory(file = ".Rhistory")
savehistory(file = ".Rhistory")

history(max.show = 25, reverse = FALSE, pattern, ...)

timestamp(stamp = date(),
          prefix = "##------ ", suffix = " ------##",
          quiet = FALSE)

Arguments

file | The name of the file in which to save the history, or from which to load it. The path is relative to the current working directory.
max.show | The maximum number of lines to show. Inf will give all of the currently available history.
reverse | logical. If true, the lines are shown in reverse order. Note: this is not useful when there are continuation lines.
pattern | A character string to be matched against the lines of the history
... | Arguments to be passed to grep when doing the matching.
stamp | A value or vector of values to be written into the history.
prefix | A prefix to apply to each line.
suffix | A suffix to apply to each line.
quiet | If TRUE, suppress printing timestamp to the console.

Details

There are several history mechanisms available for the different R consoles, which work in similar but not identical ways. Other uses of R, in particular embedded uses, may have no history. This works in Rgui and interactive Rterm but not in batch use of Rterm nor in embedded/DCOM versions.

The history mechanism is controlled by two environment variables: R_HISTSIZE controls the number of lines that are saved (default 512), and R_HISTFILE sets the filename used for the loading/saving of history if requested at the beginning/end of a session (but not the default for these functions). There is no limit on the number of lines of history retained during a session, so setting R_HISTSIZE to a large value has no penalty unless a large file is actually generated.

These variables are read at the time of saving, so can be altered within a session by the use of Sys.putenv.

history shows only unique matching lines if pattern is supplied.

The timestamp function writes a timestamp (or other message) into the history and echos it to the console. On platforms that do not support a history mechanism (where the mechanism does not yet support timestamps) only the console message is printed.

Note

If you want to save the history (almost) every session, you can put a call to savehistory() in .Last. See the examples.

Examples

## Not run:
.Last <- function()
    if(interactive()) try(savehistory("~/.Rhistory"))
## End(Not run)


Select Items from a List

Description

Select item(s) from a character vector.

Usage

select.list(list, preselect = NULL, multiple = FALSE, title = NULL)

Arguments

list | character. A list of items.
preselect | a character vector, or NULL. If non-null and if the string(s) appear in the list, the item(s) are selected initially.
multiple | logical: can more than one item be selected?
title | optional character string for window title.

Details

This brings up a modal dialog box with a (scrollable) list of items, which can be selected by the mouse. If multiple is true, further items can be selected or deselected by holding the control key down whilst selecting, and shift-clicking can be used to select ranges.

Normal termination is via the OK button or by hitting Enter. Selection can be aborted via the Cancel button or pressing Escape.

Value

A character vector of selected items. If multiple is false and no item was selected (or Cancel was used), "" is returned. If multiple is true and no item was selected (or Cancel was used) then a character vector of length 0 is returned.

See Also

menu, tk_select.list for a graphical version using Tcl/Tk.

Examples

## Not run:
select.list(sort(.packages(all.available = TRUE)))
## End(Not run)


Collect Information About the Current R Session

Description

Print version information about R and attached packages.

Usage

sessionInfo(package=NULL)
## S3 method for class 'sessionInfo':
print(x, ...)
## S3 method for class 'sessionInfo':
toLatex(object, ...)

Arguments

package | a character vector naming installed packages. By default all attached packages are used.
x | an object of class "sessionInfo".
object | an object of class "sessionInfo".
... | currently not used.

See Also

R.version

Examples

sessionInfo()
toLatex(sessionInfo())


Select Package Repositories

Description

Interact with the user to choose the package repositories to be used.

Usage

setRepositories(graphics = getOption("menu.graphics"))

Arguments

graphics Logical. If true use a listbox, otherwise use a text list in the console.

Details

The default list of known repositories is stored in the file ‘R_HOME/etc/repositories’. That file can be edited for a site, or a user can have a personal copy in ‘HOME/.R/repositories’ which will take precedence.

The items that are preselected are those that are currently in options("repos") plus those marked as default in the list of known repositories.

Value

This function is invoked mainly for its side effect of updating options("repos"). It returns (invisibly) the previous repos options setting (as a list with component repos) or NULL if no changes were applied.

See Also

chooseCRANmirror, install.packages.


Set or get the Window Title

Description

Set the title of the R window which will appear in the task bar.

Usage

setWindowTitle(suffix, title = paste(getIdentification(), suffix))

getWindowTitle()

getIdentification()

Arguments

suffix | a character string to form part of the title
title | a character string forming the complete new title

Details

setWindowTitle appends suffix to the normal window identification (RGui, R Console or Rterm). Use suffix = "" to reset the title.

getWindowTitle gets the current title.

This sets the title of the frame in MDI mode, the title of the console for RGui --sdi, and the title of the window from which it was launched for Rterm. It has no effect in embedded uses of R.

getIdentification returns the normal window identification.

Value

All three functions return a length 1 character vector.
setWindowTitle returns the previous window title (invisibly).
getWindowTitle and getIdentification return the current window title and the normal window identification, respectively.

Examples

## show the current working directory in the title, saving the old one
oldtitle <- setWindowTitle(getwd())
Sys.sleep(0.5)
## reset the title
setWindowTitle("")
Sys.sleep(0.5)
## restore the original title
setWindowTitle(title = oldtitle)


Build a DLL for Dynamic Loading

Description

The given source files are first compiled. All specified object files are then linked into a shared library which can be loaded into R using dyn.load or library.dynam.

Usage

R CMD SHLIB [options] [-o dllname] files

Arguments

files | a list of names of (typically) source files to be compiled and included in the library. You can also include the names of object files which are automagically made from their sources, and archive (*.a) and library linking commands.
dllname | the name of the shared library to be built, optionally including the extension ‘.dll’. If not given, the name of the DLL is taken from the first source or object file specified.
options | Further options to control the processing. Use R CMD SHLIB --help for a current list. The most useful one is -d to build a debug DLL.

Details

R CMD SHLIB uses the mechanism as used by INSTALL to compile source code in packages. To use SHLIB you need to have installed (from the R installer) the files for compiling source packages as well as the tools described in the ‘R Installation and Administration’ manual.

Please consult section ‘Creating shared objects’ in the manual ‘Writing R Extensions’ for how to customize it (for example to add cpp flags and to add libraries to the link step) and for details of some of its quirks.

Items in files with extensions .c, .cpp, .cc, .C, .f, .f90 and .f95 are regarded as source files, and those with extension .o as object files. All other items are passed to the linker.

See Also

dyn.load, library.dynam.

The ‘R Installation and Administration’ and ‘Writing R Extensions’ manuals.

Examples

## Not run:
rcmd SHLIB -o my.dll a.f b.f -L/AMD/acml3.5.0/gnu32/lib -lacml
## End(Not run)


Express File Paths in Short Form

Description

Convert file paths to the short (DOS) form, with 8+3 path components and no spaces. This is an interface to the Windows API call GetShortPathName.

Usage

shortPathName(path)

Arguments

path character vector of file paths.

Value

A character vector. The path separator will be \.

See Also

normalizePath.

Examples

cat(shortPathName(c(R.home(), tempdir())), sep = "\n")


Compactly Display the Structure of an Arbitrary R Object

Description

Compactly display the internal structure of an R object, a “diagnostic” function and an alternative to summary (and to some extent, dput). Ideally, only one line for each “basic” structure is displayed. It is especially well suited to compactly display the (abbreviated) contents of (possibly nested) lists. The idea is to give reasonable output for any R object. It calls args for (non-primitive) function objects.

strOptions() is a convenience function for setting options(str = .), see the examples.

Usage

str(object, ...)

## S3 method for class 'data.frame':
str(object, ...)

## Default S3 method:
str(object, max.level = NA,
    vec.len  = strO$vec.len, digits.d = strO$digits.d,
    nchar.max = 128, give.attr = TRUE, give.length = TRUE,
    width = getOption("width"), nest.lev = 0,
    indent.str = paste(rep.int(" ", max(0, nest.lev + 1)),
                       collapse = ".."),
    comp.str="$ ", no.list = FALSE, envir = baseenv(),
    strict.width = strO$strict.width, ...)

strOptions(strict.width = "no", digits.d = 3, vec.len = 4)

Arguments

object | any R object about which you want to have some information.
max.level | maximal level of nesting which is applied for displaying nested structures, e.g., a list containing sub lists. Default NA: Display all nesting levels.
vec.len | numeric (>= 0) indicating how many “first few” elements are displayed of each vector. The number is multiplied by different factors (from .5 to 3) depending on the kind of vector. Defaults to the vec.len component of option "str" (see options) which defaults to 4.
digits.d | number of digits for numerical components (as for print). Defaults to the digits.d component of option "str" which defaults to 3.
nchar.max | maximal number of characters to show for character strings. Longer strings are truncated, see longch example below.
give.attr | logical; if TRUE (default), show attributes as sub structures.
give.length | logical; if TRUE (default), indicate length (as [1:...]).
width | the page width to be used. The default is the currently active options("width"); note that this has only a weak effect, unless strict.width is not "no".
nest.lev | current nesting level in the recursive calls to str.
indent.str | the indentation string to use.
comp.str | string to be used for separating list components.
no.list | logical; if true, no “list of ..” is nor the class is printed.
envir | the environment to be used for promise (see delayedAssign) objects only.
strict.width | string indicating if the width argument's specification should be followed strictly, one of the values c("no", "cut", "wrap"). Defaults to the strict.width component of option "str" (see options) which defaults to "no" for back compatibility reasons; "wrap" uses strwrap(*, width=width) whereas "cut" cuts directly to width. Note that a small vec.length may be better than setting strict.width = "wrap".
... | potential further arguments (required for Method/Generic reasons).

Value

str does not return anything, for efficiency reasons. The obvious side effect is output to the terminal.

Author(s)

Martin Maechler maechler@stat.math.ethz.ch since 1990.

See Also

ls.str for listing objects with their structure; summary, args.

Examples

require(stats)
## The following examples show some of 'str' capabilities
str(1:12)
str(ls)
str(args) #- more useful than  args(args) !
str(freeny)
str(str)
str(.Machine, digits = 20)
str( lsfit(1:9,1:9))
str( lsfit(1:9,1:9), max = 1)
str( lsfit(1:9,1:9), width = 60, strict.width = "cut")
str( lsfit(1:9,1:9), width = 60, strict.width = "wrap")
op <- options(); str(op) # save first;
                         # otherwise internal options() is used.
need.dev <- !exists(".Device") || is.null(.Device) || .Device == "null device"
{ if(need.dev) postscript()
  str(par())
  if(need.dev) graphics.off()
}
ch <- letters[1:12]; is.na(ch) <- 3:5
str(ch) # character NA's

nchar(longch <- paste(rep(letters,100), collapse=""))
str(longch)
str(longch, nchar.max = 52)

str(longch, strict.width = "wrap")

## Settings for narrow transcript :
op <- options(width = 60,
              str = strOptions(strict.width = "wrap"))
str(lsfit(1:9,1:9))
str(options())
## reset to previous:
options(op)

str(quote( { A+B; list(C,D) } ))

## S4 classes :
require(stats4)
x <- 0:10; y <- c(26, 17, 13, 12, 20, 5, 9, 8, 5, 4, 8)
ll <- function(ymax=15, xh=6)
      -sum(dpois(y, lambda=ymax/(1+x/xh), log=TRUE))
fit <- mle(ll)
str(fit)


Summarise Output of R Sampling Profiler

Description

Summarise the output of the Rprof function to show the amount of time used by different R functions.

Usage

summaryRprof(filename = "Rprof.out", chunksize = 5000,
              memory=c("none","both","tseries","stats"),
              index=2, diff=TRUE, exclude=NULL)

Arguments

filename | Name of a file produced by Rprof()
chunksize | Number of lines to read at a time
memory | Summaries for memory information. See Details below
index | How to summarize the stack trace for memory information. See Details below.
diff | If TRUE memory summaries use change in memory rather than current memory
exclude | Functions to exclude when summarizing the stack trace for memory summaries

Details

This function is an alternative to R CMD Rprof. It provides the convenience of an all-R implementation but will be slower for large files.

As the profiling output file could be larger than available memory, it is read in blocks of chunksize lines. Increasing chunksize will make the function run faster if sufficient memory is available.

When called with memory.profiling=TRUE, the profiler writes information on three aspects of memory use: vector memory in small blocks on the R heap, vector memory in large blocks (from malloc), memory in nodes on the R heap. It also records the number of calls to the internal function duplicate in the time interval. duplicate is called by C code when arguments need to be copied. Note that the profiler does not track which function actually allocated the memory.

With memory="both" the change in total memory (truncated at zero) is reported in addition to timing data.

With memory="tseries" or memory="stats" the index argument specifies how to summarize the stack trace. A positive number specifies that many calls from the bottom of the stack; a negative number specifies the number of calls from the top of the stack. With memory="tseries" the index is used to construct labels and may be a vector to give multiple sets of labels. With memory="stats" the index must be a single number and specifies how to aggregate the data to the maximum and average of the memory statistics. With both memory="tseries" and memory="stats" the argument diff=TRUE asks for summaries of the increase in memory use over the sampling interval and diff=FALSE asks for the memory use at the end of the interval.

Value

If memory="none",a list with components

by.self | Timings sorted by ‘self’ time
by.total | Timings sorted by ‘total’ time
sampling.time | Total length of profiling run

If memory="both" the same list but with memory consumption in Mb in addition to the timings.
If memory="tseries" a data frame giving memory statistics over time
If memory="stats" a by object giving memory statistics by function.

See Also

The chapter on “Tidying and profiling R code” in “Writing R Extensions” (see the ‘doc/manual’ subdirectory of the R source tree).

Rprof

tracemem traces copying of an object via the C function duplicate.

Rprofmem is a non-sampling memory use profiler.

http://developer.r-project.org/memory-profiling.html

Examples

## Not run:
## Rprof() is not available on all platforms
Rprof(tmp <- tempfile())
example(glm)
Rprof()
summaryRprof(tmp)
unlink(tmp)
## End(Not run)


Automatic Generation of Reports

Description

Sweave provides a flexible framework for mixing text and S code for automatic report generation. The basic idea is to replace the S code with its output, such that the final document only contains the text and the output of the statistical anlysis.

Usage

Sweave(file, driver = RweaveLatex(),
       syntax = getOption("SweaveSyntax"), ...)

Stangle(file, driver = Rtangle(),
        syntax = getOption("SweaveSyntax"), ...)

Arguments

file | Name of Sweave source file.
driver | The actual workhorse, see details below.
syntax | An object of class SweaveSyntax or a character string with its name. The default installation provides SweaveSyntaxNoweb and SweaveSyntaxLatex.
... | Further arguments passed to the driver's setup function.

Details

Automatic generation of reports by mixing word processing markup (like latex) and S code. The S code gets replaced by its output (text or graphs) in the final markup file. This allows to re-generate a report if the input data change and documents the code to reproduce the analysis in the same file that also produces the report.

Sweave combines the documentation and code chunks together (or their output) into a single document. Stangle extracts only the code from the Sweave file creating a valid S source file (that can be run using source). Code inside \Sexpr{} statements is ignored by Stangle.

Stangle is just a frontend to Sweave using a simple driver by default, which discards the documentation and concatenates all code chunks the current S engine understands.

Hook Functions

Before each code chunk is evaluated, a number of hook functions can be executed. If getOption("SweaveHooks") is set, it is taken to be a collection of hook functions. For each logical option of a code chunk (echo, print, ...) a hook can be specified, which is executed if and only if the respective option is TRUE. Hooks must be named elements of the list returned by getOption("SweaveHooks") and be functions taking no arguments. E.g., if option "SweaveHooks" is defined as list(fig = foo), and foo is a function, then it would be executed before the code in each figure chunk. This is especially useful to set defaults for the graphical parameters in a series of figure chunks.

Note that the user is free to define new Sweave options and associate arbitrary hooks with them. E.g., one could define a hook function for option clean that removes all objects in the global environment. Then all code chunks with clean = TRUE would start operating on an empty workspace.

Syntax Definition

Sweave allows a very flexible syntax framework for marking documentation and text chunks. The default is a noweb-style syntax, as alternative a latex-style syntax can be used. See the user manual for details.

Author(s)

Friedrich Leisch

References

Friedrich Leisch: Sweave User Manual, 2002
http://www.ci.tuwien.ac.at/~leisch/Sweave

Friedrich Leisch: Dynamic generation of statistical reports using literate data analysis. In W. Härdle and B. Rönz, editors, Compstat 2002 - Proceedings in Computational Statistics, pages 575–580. Physika Verlag, Heidelberg, Germany, 2002. ISBN 3-7908-1517-9.

See Also

RweaveLatex, Rtangle

Examples

testfile <- system.file("Sweave", "Sweave-test-1.Rnw", package = "utils")

## enforce par(ask=FALSE)
options(par.ask.default=FALSE)

## create a LaTeX file
Sweave(testfile)

## create an S source file from the code chunks
Stangle(testfile)
## which can be simply sourced
source("Sweave-test-1.R")


Convert Sweave Syntax

Description

This function converts the syntax of files in Sweave format to another Sweave syntax definition.

Usage

SweaveSyntConv(file, syntax, output = NULL)

Arguments

file | Name of Sweave source file.
syntax | An object of class SweaveSyntax or a character string with its name giving the target syntax to which the file is converted.
output | Name of output file, default is to remove the extension from the input file and to add the default extension of the target syntax. Any directory names in file are also removed such that the output is created in the current working directory.

Author(s)

Friedrich Leisch

References

Friedrich Leisch: Sweave User Manual, 2002
http://www.ci.tuwien.ac.at/~leisch/Sweave

See Also

RweaveLatex, Rtangle

Examples

testfile <- system.file("Sweave", "Sweave-test-1.Rnw", package = "utils")

## convert the file to latex syntax
SweaveSyntConv(testfile, SweaveSyntaxLatex)

## and run it through Sweave
Sweave("Sweave-test-1.Stex")


Sweave Driver Utilities

Description

These functions are handy for writing Sweave drivers and currently not documented. Look at the source code of the Sweave Latex driver (in this package) or the HTML driver (in the R2HTML package from CRAN) to see how they can be used.

Usage

RtangleWritedoc(object, chunk)
RweaveChunkPrefix(options)
RweaveEvalWithOpt(expr, options)
RweaveLatexOptions(options)
RweaveTryStop(err, options)
SweaveHooks(options, run = FALSE, envir = .GlobalEnv)

Author(s)

Friedrich Leisch


Converting R Objects to BibTeX or LaTeX

Description

These methods convert R objects to character vectors with BibTeX or LaTeX markup.

Usage

toBibtex(object, ...)
toLatex(object, ...)
## S3 method for class 'Bibtex':
print(x, prefix="", ...)
## S3 method for class 'Latex':
print(x, prefix="", ...)

Arguments

object | object of a class for which a toBibtex or toLatex method exists.
x | object of class "Bibtex" or "Latex".
prefix | a character string which is printed at the beginning of each line, mostly used to insert whitespace for indentation.
... | currently not used in the print methods.

Details

Objects of class "Bibtex" or "Latex" are simply character vectors where each element holds one line of the corresponding BibTeX or LaTeX file.

See Also

citEntry and sessionInfo for examples


Trace copying of objects

Description

This function marks an object so that a message is printed whenever the internal function duplicate is called. This happens when two objects share the same memory and one of them is modified. It is a major cause of hard-to-predict memory use in R.

Usage

tracemem(x)
untracemem(x)
retracemem(x, previous=NULL)

Arguments

x | An R object, not a function or environment or NULL
previous | An address specification as returned by tracemem or retracemem

Details

This functionality is optional, determined at compilation, because it makes R run a little more slowly even when no objects are being traced. tracemem and untracemem give errors when R is not compiled with memory profiling; retracemem does not (so it can be left in code during development).

When an object is traced any copying of the object by the C function duplicate or by arithmetic or mathmetical operations produces a message to standard output. The message consists of the string memtrace, the identifying strings for the object being copied and the new object being created, and a stack trace showing where the duplication occurred. retracemem() is used to indicate that a variable should be considered a copy of a previous variable (eg after subscripting).

The messages can be turned off with tracingState.

It is not possible to trace functions, as this would conflict with trace and it is not useful to trace NULL, environments, promises, weak references, or external pointer objects, as these are not duplicated.

Value

A string for identifying the object in the trace output.

See Also

trace

Rprofmem

http://developer.r-project.org/memory-profiling.html

Examples

## Not run:
a<-1:10
tracemem(a)
## b and a share memory
b<-a
b[1]<-1

## copying in lm
d<-rnorm(10)
tracemem(d)
lm(d~a+log(b))

## f is not a copy and is not traced
f<-d[-1]
f+1
## indicate that f should be traced as a copy of d
retracemem(f, retracemem(d))
f+1

## End(Not run)


Download Packages from CRAN-like repositories

Description

These functions can be used to automatically compare the version numbers of installed packages with the newest available version on the repositories and update outdated packages on the fly.

Usage

update.packages(lib.loc = NULL, repos = getOption("repos"),
                contriburl = contrib.url(repos, type),
                method, instlib = NULL, ask = TRUE, available = NULL,
                ..., checkBuilt = FALSE,
                type = getOption("pkgType"))

available.packages(contriburl = contrib.url(getOption("repos")),
                   method, fields = NULL)

old.packages(lib.loc = NULL, repos = getOption("repos"),
             contriburl = contrib.url(repos),
             method, available = NULL, checkBuilt = FALSE)

new.packages(lib.loc = NULL, repos = getOption("repos"),
             contriburl = contrib.url(repos, type),
             method, available = NULL, ask = FALSE, ...,
             type = getOption("pkgType"))

download.packages(pkgs, destdir, available = NULL,
                  repos = getOption("repos"),
                  contriburl = contrib.url(repos, type),
                  method, type = getOption("pkgType"))

install.packages(pkgs, lib, repos = getOption("repos"),
                 contriburl = contrib.url(repos, type),
                 method, available = NULL, destdir = NULL,
                 installWithVers = FALSE, dependencies = FALSE,
                 type = getOption("pkgType"),
                 configure.args = character(0),
                 clean = FALSE)

contrib.url(repos, type = getOption("pkgType"))

Arguments

lib.loc | character vector describing the location of R library trees to search through (and update packages therein).
repos | character vector, the base URL(s) of the repositories to use, i.e., the URL of the CRAN master such as "http://cran.r-project.org" or its Statlib mirror, "http://lib.stat.cmu.edu/R/CRAN". Can be NULL to install from local ‘.zip’ files.
contriburl | URL(s) of the contrib sections of the repositories. Use this argument only if your repository mirror is incomplete, e.g., because you burned only the ‘contrib’ section on a CD. Overrides argument repos. Can also be NULL to install from local ‘.zip’ files.
method | Download method, see download.file.
pkgs | character vector of the short names of packages/bundles whose current versions should be downloaded from the repositories. If repos = NULL, a character vector of file paths of ‘.zip’ files. If this is a zero-length character vector, a listbox of available packages (including those contained in bundles) is presented where possible.
destdir | directory where downloaded packages are stored.
available | an object listing packages available at the repositories as returned by available.packages.
lib | character vector giving the library directories where to install the packages. Recycled as needed. If missing, defaults to .libPaths()[1].
ask | logical indicating whether to ask user before packages are actually downloaded and installed, or the character string "graphics", which brings up a widget to allow the user to (de-)select from the list of packages which could be updated. The latter only works on systems with a GUI version of select.list, and is otherwise equivalent to ask = TRUE.
installWithVers | If TRUE, will invoke the install of the package such that it can be referenced by package version.
checkBuilt | If TRUE, a package built under an earlier minor version of R is considered to be ‘old’.
instlib | character string giving the library directory where to install the packages.
dependencies | logical indicating to also install uninstalled packages on which these packages depend/suggest/import (and so on recursively). Not used if repos = NULL. Can also be a character vector, a subset of c("Depends", "Imports", "Suggests"). Only supported if lib is of length one (or missing), so it is unambiguous where to install the dependent packages.
configure.args | a character vector or a named list. If a character vector with no names is supplied, the elements are concatenated into a single string (separated by a space) and used as the value for the --configure-args flag in the call to R CMD INSTALL. If the character vector has names, these are assumed to identify values for --configure-args for individual packages. This allows one to specify settings for an entire collection of packages which will be used if any of those packages are installed. These settings can therefore be reused and act as default settings. A named list can be used also to the same effect, and that allows multi-element character strings for each package which are concatenated to a single string to be used as the value for --configure-args.
... | (for update.packages). Arguments such as destdir, installWithVers and dependencies to be passed to install.packages. (for new.packages). Arguments such as destdir and dependencies to be passed to install.packages.
type | character, indicating the type of package to download and install. Possible values are "win.binary" (the default) and "source" (for which suitable tools need to be installed: see the ‘rw-FAQ’). Value "mac.binary" can be used to explore and download Mac OS X binaries.
clean | a logical value indicating whether to specify to add the --clean flag to the call to R CMD INSTALL. This is sometimes used to perform additional operations at the end of the package installation in addition to removing intermediate files.
fields | a character vector giving the fields to extract from the PACKAGES file(s) in addition to the default ones, or NULL (default). Unavailable fields result in NA values.

Details

All of these functions work with the names of a package or bundle (and not the component packages of a bundle, except for install.packages if the repository provides the necessary information).

available.packages returns a matrix of details corresponding to packages/bundles currently available at one or more repositories. The current list of packages is downloaded over the internet (or copied from a local mirror). It returns only packages whose version requirements are met by the running version of R.

old.packages compares the information from available.packages with that from installed.packages and reports installed packages/bundles that have newer versions on the repositories or, if checkBuilt = TRUE, that were built under an earlier minor version of R (for example built under 2.0.x when running R 2.1.1). (There is no check that the version on the repository was built under the current minor version of R, but it is advertised as being suitable for this version.)

new.packages does the same comparison but reports uninstalled packages/bundles that are available at the repositories. It will also give warnings about incompletely installed bundles (provided the information is available) and bundles whose contents has changed. If ask != FALSE it asks which packages should be installed in the first element of lib.loc. NB: versioned installs are not installs of a named package.

download.packages takes a list of package/bundle names and a destination directory, downloads the newest versions and saves them in destdir. If the list of available packages is not given as argument, it is obtained from repositories. If a repository is local, i.e., the URL starts with "file:", then the packages are not downloaded but used directly. (Both "file:" and "file:///" are allowed as prefixes to a file path, the latter for an absolute file path.)

The main function of the set is update.packages. First a list of all packages/bundles found in lib.loc is created and compared with those available at the repostories. If ask = TRUE (the default) packages/bundles with a newer version are reported and for each one the user can specify if it should be updated. If so, the pre-compiled packages are downloaded from the repositories and installed in the respective library path (or instlib if specified).

install.packages can be used to install new packages/bundles. It takes a vector of names and a destination library, downloads the packages from the repositories and installs them. (If the library is omitted it defaults to the first directory in .libPaths(), with a warning if there is more than one.) Argument pkgs can also be a character vector of file names of zip files if repos = NULL. The zip files are then unpacked directly.

contrib.url adds the appropriate type-specific path within a repository to each URL in repos.

For install.packages, destdir is the directory to which packages will be downloaded. If it is NULL (the default) a directory downloaded_packages of the session temporary directory will be used (and the files will be deleted at the end of the session).

If repos or contriburl is a vector of length greater than one, the newest version of the package compatible with this version of R is fetched from the first repository on the list within which it is found.

Value

For available.packages, a matrix with one row per package/bundle, row names the package names and column names "Package", "Version", "Priority", "Bundle", "Depends", "Imports", "Suggests" "Contains" and "Repository". Additional columns can be specified using the fields argument.
For old.packages, NULL or a matrix with one row per package/bundle, row names the package names and column names "Package", "LibPath", "Installed" (the version), "Built" (the version built under), "ReposVer" and "Repository".
For new.packages a character vector of package/bundle names, after any have been installed.
For download.packages, a two-column matrix of names and destination file names, for those packages/bundles successfully downloaded. If packages are not available or there is a problem with the download, suitable warnings are given.
install.packages and update.packages have no return value.

Warning

Take care when using dependencies with update.packages, for it is unclear where new dependencies should be installed. The current implementation will only allow it if all the packages to be updated are in a single library, when that library will be used.

Note

Some binary distributions of R have INSTALL in a separate bundle, e.g. an R-devel RPM. install.packages will give an error if called on such a system.

See Also

installed.packages, remove.packages

See download.file for how to handle proxies and other options to monitor file transfers.

INSTALL, REMOVE, library, .packages, read.dcf

Examples

## Not run:
  install.packages(c("XML_0.99-5.tar.gz",
                     "../../Interfaces/Perl/RSPerl_0.8-0.tar.gz"),
                   repos = NULL,
                   configure.args = c(XML = '--with-xml-config=xml-config',
                                      RSPerl = "--with-modules='IO Fcntl'"))
## End(Not run)


Display a text URL

Description

Extension of file.show to display text files from a remote server.

Usage

url.show(url, title = url, file = tempfile(),
         delete.file = TRUE, method, ...)

Arguments

url | The URL to read from.
title | Title for the browser.
file | File to copy to.
delete.file | Delete the file afterwards?
method | File transfer method: see download.file
... | Arguments to pass to file.show.

See Also

url, file.show, download.file

Examples

## Not run: url.show("http://lib.stat.cmu.edu/datasets/csb/ch3a.txt")


Encode or Decode a (partial) URL

Description

Functions to encode or decode characters in URLs.

Usage

URLencode(URL, reserved = FALSE)
URLdecode(URL)

Arguments

URL | A character string.
reserved | should reserved characters be encoded? See Details.

Details

Characters in a URL other than the English alphanumeric characters and $ - _ . + ! * ' ( ) , should be encoded as % plus a two-digit hexadecimal representation, and any single-byte character can be so encoded. (Multi-byte characters are encoded as byte-by-byte.)

In addition, ; / ? : @ = & are reserved characters, and should be encoded unless used in their reserved sense, which is scheme specific. The default in URLencode is to leave them alone, which is appropriate for file:// URLs, but probably not for http:// ones.

Value

A character string.

References

RFC1738, http://www.rfc-editor.org/rfc/rfc1738.txt

Examples

(y <- URLencode("a url with spaces and / and @"))
URLdecode(y)
(y <- URLencode("a url with spaces and / and @", reserved=TRUE))
URLdecode(y)
URLdecode("ab%20cd")


Defunct Functions in Package utils

Description

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

Usage

package.contents(pkg, lib.loc = NULL)

See Also

utils-deprecated, Deprecated, Defunct


Deprecated Functions in Package utils

Description

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

Usage

CRAN.packages(CRAN = getOption("repos"), method,
              contriburl = contrib.url(CRAN))

Arguments

CRAN | character, an earlier way to specify a repository.
method | Download method, see download.file.
contriburl | URL(s) of the contrib section of the repositories. Use this argument only if your CRAN mirror is incomplete, e.g., because you burned only the ‘contrib’ section on a CD. Overrides argument repos.

See Also

Deprecated, Defunct


The R Utils Package

Description

R utility functions

Details

This package contains a collection of utility functions.

For a complete list, use library(help="utils").

Author(s)

R Development Core Team and contributors worldwide

Maintainer: R Core Team R-core@r-project.org


View or List Vignettes

Description

View a specified vignette, or list the available ones.

Usage

vignette(topic, package = NULL, lib.loc = NULL)

## S3 method for class 'vignette':
print(x, ...)
## S3 method for class 'vignette':
edit(name, ...)

Arguments

topic | a character string giving the (base) name of the vignette to view. If omitted, all vignettes from all installed packages are listed.
package | a character vector with the names of packages to search through, or NULL in which case all available packages in the library trees specified by lib.loc are searched.
lib.loc | a character vector of directory names of R libraries, or NULL. The default value of NULL corresponds to all libraries currently known.
x, name | Object of class vignette.
... | Ignored by the print method, passed on to file.edit by the edit method.

Details

Function vignette returns an object of the same class, the print method opens a viewer for it. Currently, only PDF versions of vignettes can be viewed. If several vignettes have PDF versions with base name identical to topic, the first one found is used.

If no topics are given, all available vignettes are listed. The corresponding information is returned in an object of class "packageIQR".

The edit method extracts the R code from the vignette to a temporary file and opens the file in an editor (see edit). This makes it very easy to execute the commands line by line, modify them in any way you want to help you test variants, etc.. An alternative way of extracting the R code from the vignette is to run Stangle on the source code of the vignette, see the examples below.

Examples

## List vignettes from all *installed* packages (can take long!):
vignette()

## Not run:
## Open the grid intro vignette
vignette("grid")

## The same
v1 <- vignette("grid")
print(v1)

## Now let us have a closer look at the code
edit(v1)

## An alternative way of extracting the code,
## R file is written to current working directory
Stangle(v1$file)

## A package can have more than one vignette (package grid has several):
vignette(package="grid")
vignette("rotated")
## The same, but without searching for it:
vignette("rotated", package="grid")
## End(Not run)


Dialog Boxes under Windows

Description

Put up a Windows dialog box to communicate with the user. There are various types, either for the user to select from a set of buttons or to edit a string.

Usage

winDialog(type = c("ok", "okcancel", "yesno", "yesnocancel"), message)
winDialogString(message, default)

Arguments

type | character. The type of dialog box. It will have the buttons implied by its name.
message | character. The information field of the dialog box. Limited to 255 chars (by Windows, checked by R).
default | character. The default string.

Value

For winDialog a character string giving the name of the button pressed (in capitals) or NULL (invisibly) if the user had no choice.
For winDialogString a string giving the contents of the text box when Ok was pressed, or NULL if Cancel was pressed.

Note

The standard keyboard accelerators work with these dialog boxes: where appropriate Return accepts the default action, Esc cancels and the underlined initial letter (Y or N) can be used.

See Also

winMenuAdd
file.choose to select a file
package windlgs in the package source distribution for ways to program dialogs in C in the GraphApp toolkit.

Examples

## Not run: winDialog("yesno", "Is it OK to delete file blah")


Auxiliary Functions for the Windows Port

Description

Auxiliary functions for the Windows port

Usage

win.version()
zip.unpack(zipname, dest)

Arguments

zipname | character string giving name of zip file.
dest | character string giving directory within which to unpack.

Details

win.version is an auxiliary function for bug.report which returns a character string describing the version of Windows in use.

zip.unpack unpacks the zip file zipname in directory dest: it is an internal version of unzip zipfile -d dest (but will use an external unzip if one is set in options("unzip")). The result is an error code, with an attribute "extracted" listing the full paths to the extracted files.


User Menus under Windows

Description

Enables users to add, delete and program menus under Windows.

Usage

winMenuAdd(menuname)
winMenuAddItem(menuname, itemname, action)
winMenuDel(menuname)
winMenuDelItem(menuname, itemname)
winMenuNames()
winMenuItems(menuname)

Arguments

menuname | a character string naming a menu.
itemname | a character string naming a menu item on an existing menu.
action | a character string describing the action when that menu is selected, or "enable" or "disable".

Details

User menus are added to the right of existing menus, and items are added at the bottom of the menu.

By default the action character string is treated as R input, being echoed on the command line and parsed and executed as usual.

If the menuname parameter of winMenuAddItem does not already exist, it will be created automatically.

Normally new submenus and menu items are added to the main console menu. They may be added elsewhere using the following special names:

$ConsoleMain
The console menu (the default)
$ConsolePopup
The console popup menu
$Graph<n>Main
The menu for graphics window <n>
$Graph<n>Popup
The popup menu for graphics window <n>

Specifying an existing item in winMenuAddItem enables the action to be changed.

Submenus can be specified by separating the elements in menuname by slashes: as a consequence menu names may not contain slashes.

If the action is specified as "none" no action is taken: this can be useful to reserve items for future expansion.

The function winMenuNames can be used to find out what menus have been created by the user and returns a vector of the existing menu names.

The winMenuItems function will take the name of a menu and return the items that exist in that menu. The return value is a named vector where the names correspond to the names of the items and the values of the vector are the corresponding actions.

The winMenuDel function will delete a menu and all of its items and submenus. winMenuDelItem just deletes one menu item.

The total path to an item (menu string plus item string) cannot exceed 1000 bytes, and the menu string cannot exceed 500 bytes.

Value

NULL, invisibly. If an error occurs, an informative error message will be given.

See Also

winDialog

Examples

## Not run:
winMenuAdd("Testit")
winMenuAddItem("Testit", "one", "aaaa")
winMenuAddItem("Testit", "two", "bbbb")
winMenuAdd("Testit/extras")
winMenuAddItem("Testit", "-", "")
winMenuAddItem("Testit", "two", "disable")
winMenuAddItem("Testit", "three", "cccc")
winMenuAddItem("Testit/extras", "one more", "ddd")
winMenuAddItem("Testit/extras", "and another", "eee")
winMenuAdd("$ConsolePopup/Testit")
winMenuAddItem("$ConsolePopup/Testit", "six", "fff")
winMenuNames()
winMenuItems("Testit")
## End(Not run)