Appendix: R Reference - R in a Nutshell
Pages: 1, 2, 3, 4, 5

## stats

This package contains functions to perform a wide varietyof statistical analyses.

### Functions

FunctionDescription
AICGeneric function for calculating the Akaike informationcriterion for one or several fitted model objects for which alog-likelihood value can be obtained, according to the formula−2 ∗ log-likelihood + knpar, wherenpar representsthe number of parameters in the fitted model, and k= 2 for the usual AIC, or k =log(n) (n is thenumber of observations) for the so-called Bayesian informationcriterion (BIC) or Schwarz's Bayesian criterion (SBC).
ARMAacfComputes the theoretical autocorrelation function orpartial autocorrelation function for an autoregressive movingaverage (ARMA) process.
ARMAtoMAConverts an ARMA process to an infinite moving average(MA) process.
Box.testComputes the Box-Pierce or Ljung-Box test statistic forexamining the null hypothesis of independence in a given timeseries. These are sometimes known as "portmanteau"tests.
CSets the `"contrasts"`attribute for the factor.
DComputes derivatives of simple expressions, symbolically.
GammaFamily object for Gamma distributions (used byfunctions such as `glm`).
HoltWintersComputes Holt-Winters filtering of a given time series.Unknown parameters are determined by minimizing the squaredprediction error.
IQRComputes the interquartile range of the `x` values.
KalmanForecast, KalmanLike, KalmanRun, KalmanSmoothUse Kalman filtering to find the (Gaussian)log-likelihood, or for forecasting or smoothing.
NLSstAsymptoticFits the asymptotic regression model, in the form`b0 + b1*(1-exp(-exp(lrc) *x)`, to the `xy`data. This can be used as a building block in determiningstarting estimates for more complicated models.
NLSstClosestXUses inverse linear interpolation to approximate the`x` value at which thefunction represented by `xy`is equal to `yval`.
NLSstLfAsymptoteProvides an initial guess at the horizontal asymptoteon the left side (i.e., small values of `x`) of the graph of `y` versus `x` from the `xy` object. Primarily used within`initial` functions forself-starting nonlinear regression models.
NLSstRtAsymptoteProvides an initial guess at the horizontal asymptoteon the right side (i.e., large values of `x`) of the graph of `y` versus `x` from the `xy` object. Primarily used within`initial` functions forself-starting nonlinear regression models.
PP.testComputes the Phillips-Perron test for the nullhypothesis that `x` has aunit root against a stationary alternative.
SSDFunction to compute the matrix of residual sums ofsquares and products, or the estimated variance matrix formultivariate linear models.
SSasympThis `selfStart` modelevaluates the asymptotic regression function and its gradient.It has an `initial` attributethat will evaluate initial estimates of the parameters`Asym`, `R0`, and `lrc` for a given set of data.
SSasympOffThis `selfStart` modelevaluates an alternative parametrization of the asymptoticregression function and the gradient with respect to thoseparameters. It has an `initial` attribute that createsinitial estimates of the parameters `Asym`, `lrc`, and `c0`.
SSasympOrigThis `selfStart` modelevaluates the asymptotic regression function through theorigin and its gradient. It has an `initial` attribute that will evaluateinitial estimates of the parameters `Asym` and `lrc` for a given set of data.
SSbiexpThis `selfStart` modelevaluates the biexponential model function and its gradient.It has an `initial` attributethat creates initial estimates of the parameters `A1`, `lrc1`, `A2`, and `lrc2`.
SSfolThis `selfStart` modelevaluates the first-order compartment function and itsgradient. It has an `initial`attribute that creates initial estimates of the parameters`lKe`, `lKa`, and `lCl`.
SSfplThis `selfStart` modelevaluates the four-parameter logistic function and itsgradient. It has an `initial`attribute that will evaluate initial estimates of theparameters `A`, `B`, `xmid`, and `scal` for a given set ofdata.
SSgompertzThis `selfStart` modelevaluates the Gompertz growth model and its gradient. It hasan `initial` attribute thatcreates initial estimates of the parameters `Asym`, `b2`, and `b3`.
SSlogisThis `selfStart` modelevaluates the logistic function and its gradient. It has an`initial` attribute thatcreates initial estimates of the parameters `Asym`, `xmid`, and `scal`.
SSmicmenThis `selfStart` modelevaluates the Michaelis-Menten model and its gradient. It hasan `initial` attribute that willevaluate initial estimates of the parameters `Vm` and `K`.
SSweibullThis `selfStart` modelevaluates the Weibull model for growth curve data and itsgradient. It has an `initial`attribute that will evaluate initial estimates of theparameters `Asym`, `Drop`, `lrc`, and `pwr` for a given set of data.
StructTSFits a structural model for a time series by maximumlikelihood.
TukeyHSDCreates a set of confidence intervals on thedifferences between the means of the levels of a factor withthe specified family-wise probability of coverage. Theintervals are based on the Studentized range statistic, Tukey's honest significant difference method. There is a`plot` method.
TukeyHSD.aovCreates a set of confidence intervals on thedifferences between the means of the levels of a factor withthe specified family-wise probability of coverage. Theintervals are based on the Studentized range statistic, Tukey's honest significant difference method. There is a`plot` method.
acfThe function `acf`computes (and by default plots) estimates of theautocovariance or autocorrelation function. The function`pacf` is the function usedfor partial autocorrelations. The function `ccf` computes the cross-correlationor cross-covariance oftwo univariate series.
acf2ARComputes an AR process exactly fitting anautocorrelation function.
add.scope`add.scope` and`drop.scope` compute thoseterms that can be individually added to or dropped from amodel while respecting the hierarchy of terms.
add1Computes all the single terms in the `scope` argument that can be added toor dropped from the model, fits those models, and computes atable of the changes in fit.
addmarginsFor a given table, one can specify which of theclassifying factors to expand by one or more levels to holdmargins to be calculated. One may, for example, form sums andmeans over the first dimension and medians over the second.The resulting table will then have two extra levels for thefirst dimension and one extra level for the second. Thedefault is to sum over all margins in the table. Otherpossibilities may give results that depend on the order inwhich the margins are computed. This is flagged in the printedoutput from the function.
aggregateSplits the data into subsets, computes summarystatistics for each, and returns the result in a convenientform.
aliasFinds aliases (linearly dependent terms) in a linearmodel specified by a formula.
anovaComputes analysis of variance (or deviance) tables forone or more fitted model objects.
anova.lmlistComputes an analysis of variance table for one or morelinear model fits.
aovFits an analysis of variance model by a call to`lm` for eachstratum.
approxReturns a list of points that linearly interpolategiven data points, or a function performing the linear (orconstant) interpolation.
approxfunReturns a list of points that linearly interpolategiven data points, or a function performing the linear (orconstant) interpolation.
arFits an autoregressive time series model to the data, by default selecting the complexity by AIC.
arimaFits an ARIMA model to a univariate timeseries.
arima.simSimulates from an ARIMA model.
arima0Fits an ARIMA model to a univariate time series andforecasts from the fitted model.
as.dendrogramCoerces an object to class `"dendrogram"` (which provides generalfunctions for handling treelike structures).
as.distCoerces to a dist object (a matrix returned by the distfunction).
as.formulaThe generic function `formula` and its specific methodsprovide a way of extracting formulas that have been includedin other objects. `as.formula` is almost identical, additionally preserving attributes when `object` already inherits from`"formula"`.
as.hclustConverts objects from other hierarchical clusteringfunctions to class `"hclust"`.
as.stepfunGiven the vectors (x[1], ..., x[n]) and (y[0], y[1], ..., y[n]) (one value more!), `stepfun(x, y, ...)` returns an interpolating "step" function, say`fn`. That is, fn(t) = c_i{[i]}(constant) for t in (x[i], x[i+1]) and at the abscissa values, if (by default) `right =FALSE`, fn(x_i) = y_i{fn(x[i]) =y[i]} and for `right = TRUE`, fn(x[i]) = y[i-1], for i=1, ..., n.
as.tsCoerces an object to a `ts` object.
asOneSidedFormulaNames, expressions, numeric values, and characterstrings are converted to one-sided formulas. If `object` is a formula, it must be onesided, in which case it is returned unaltered.
aveSubsets of `x[]` areaveraged, where each subset consists of those observationswith the same factor levels.
bandwidth.kernelReturns the equivalent bandwidth for a `tskernel` object.
bartlett.testPerforms Bartlett's test of the null that the variancesin each of the groups (samples) are the same.
binom.testPerforms an exact test of a simple null hypothesisabout the probability of success in a Bernoulliexperiment.
binomialFamily function for binomial distributions (used byfunctions such as `glm`).
biplotPlots a biplot on the current graphics device.
bw.SJ, bw.bcv, bw.nrd, bw.nrd0, bw.ucvBandwidth selectors for Gaussian kernels in `density`.
cancorComputes the canonical correlations between two datamatrices.
case.namesSimple utility returning (nonmissing) case names and(noneliminated) variable names.
ccfThe function `acf`computes (and by default plots) estimates of theautocovariance or autocorrelation function. The function`pacf` is the function usedfor partial autocorrelations. The function `ccf` computes the cross-correlationor cross-covariance oftwo univariate series.
chisq.testPerforms chi-squared contingency table tests andgoodness-of-fit tests.
clearNamesSets the `names`attribute of `object` to`NULL` and returns theobject.
cmdscaleClassical multidimensional scaling of a data matrix.Also known as principal coordinatesanalysis.
coef, coefficients`coef` is a genericfunction that extracts model coefficients from objectsreturned by modeling functions. `coefficients` is an alias forit.
complete.casesReturns a logical vector indicating which cases arecomplete, i.e., have no missing values.
confintComputes confidence intervals for one or moreparameters in a fitted model.
constrOptimMinimizes a function subject to linear inequalityconstraints using an adaptive barrier algorithm.
contr.SAS, contr.helmert, contr.poly, contr.sum, contr.treatmentReturn a matrix of contrasts.
contrasts, contrasts<-Set and view the contrasts associated with afactor.
convolveUses the fast Fourier transform to compute the severalkinds of convolutions of two sequences.
cooks.distanceComputes "Cook's distance" on a model object.
copheneticComputes the cophenetic distances for a hierarchicalclustering.
corComputes the correlation of two vectors, or the columnsof two matrices.
cor.testTests for association between paired samples, using oneof Pearson's product-moment correlation coefficient, Kendall'stau, or Spearman's rho.
covComputes the covariance of two vectors, or the columnsof two matrices.
cov.wtReturns a list containing estimates of the weightedcovariance matrix and the mean of the data and optionally ofthe (weighted) correlation matrix.
cov2cor`var`, `cov`, and `cor` compute the variance of `x` and the covariance or correlationof `x` and `y` if these are vectors. If `x` and `y` are matrices, then the covariances(or correlations) between the columns of `x` and the columns of `y` are computed. `cov2cor` scales a covariance matrixinto the corresponding correlation matrixefficiently.
covratioReturns the covariance ratio (for regressiondiagnostics) on a model object.
cpgramPlots a cumulative periodogram.
cutreeCuts a tree, e.g., resulting from `hclust`, into several groups byspecifying either the desired number(s) of groups or the cutheight(s).
cycle`time` creates thevector of times at which a time series was sampled. `cycle` gives the positions in thecycle of each observation. `frequency` returns the number ofsamples per unit time, and `deltat` gives the timeinterval between observations (see `ts`).
dbetaDensity function for the Beta distribution.
dbinomDensity function for the binomial distribution.
dcauchyDensity function for the Cauchy distribution.
dchisqDensity function for the chi-squareddistribution.
decomposeDecomposes a time series into seasonal, trend, andirregular components using moving averages. Deals withadditive or multiplicative seasonal components.
delete.responseReturns a `terms`object for the same model but with no responsevariable.
deltat`time` creates thevector of times at which a time series was sampled. `cycle` gives the positions in thecycle of each observation. `frequency` returns the number ofsamples per unit time, and `deltat` gives the timeinterval between observations (see `ts`).
dendrapplyApplies function `FUN`to each node of a `dendrogram` recursively. When`y <- dendrapply(x, fn)`, then `y` is a dendrogram ofthe same graph structure as `x` and for each node, `y.node[j] <- FUN(x.node[j], ...)`(where `y.node[j]` is an(invalid!) notation for the jth node of y).
densityThe (S3) generic function `density` computes kernel densityestimates. Its default method does so with the given kerneland bandwidth for univariate observations.
density.defaultThe (S3) generic function `density` computes kernel densityestimates. Its default method does so with the given kerneland bandwidth for univariate observations.
deriv, deriv3Compute derivatives of simple expressions, symbolically.
devianceReturns the deviance of a fitted model object.
dexpDensity function for the exponentialdistribution.
dfDensity, distribution function, quantile function, andrandom generation for the F-distributionwith `df1` and `df2` degrees of freedom (and optionalnoncentrality parameter `ncp`).
df.kernelThe `"tskernel"` classis designed to represent discrete symmetric normalizedsmoothing kernels. These kernels can be used to smoothvectors, matrices, or time series objects. There are `print`, `plot`, and `[` methods for these kernelobjects.
df.residualReturns the residual degrees of freedom extracted froma fitted model object.
dfbetaReturns dfbeta for a model object (for regressiondiagnostics).
dfbetasReturns dfbetas for a model object (for regressiondiagnostics).
dffitsReturns dffits for a model object (for regressiondiagnostics).
dgammaDensity function for the Gamma distribution.
dgeomDensity, distribution function, quantile function, andrandom generation for the geometric distribution withparameter `prob`.
dhyperDensity function for the hypergeometricdistribution.
diff.tsMethods for objects of class `"ts"`, typically the result of`ts`.
diffinvComputes the inverse function of the lagged differencesfunction `diff`.
distComputes and returns the distance matrix computed byusing the specified distance measure to compute the distancesbetween the rows of a data matrix.
dlnormDensity function for the log-normaldistribution.
dlogisDensity function for the logistic distribution.
dmultinomGenerates multinomially distributed random numbervectors and computes multinomialprobabilities.
dnbinomDensity function for the negative binomialdistribution.
dnormDensity function for the normal distribution.
dpoisDensity function for the Poisson distribution.
drop.scope`add.scope` and`drop.scope` compute thoseterms that can be individually added to or dropped from amodel while respecting the hierarchy of terms.
drop.terms`delete.response`returns a `terms` object forthe same model, but with no response variable. `drop.terms` removes variables fromthe righthand side of the model. There is also a `"[.terms"` method to perform the samefunction (with `keep.response=TRUE`). `reformulate` creates aformula from a character vector.
drop1Computes all the single terms in the `scope` argument that can be added toor dropped from the model, fits those models, and computes atable of the changes in fit.
dsignrankDensity, distribution function, quantile function, andrandom generation for the distribution of the Wilcoxon signedrank statistic obtained from a sample with size `n`.
dtDensity, distribution function, quantile function, andrandom generation for the t-distributionwith `df` degrees of freedom(and optional noncentrality parameter `ncp`).
dummy.coefExtracts coefficients in terms of the original levelsof the coefficients rather than the coded variables.
dunifDensity function for the uniform distribution.
dweibullDensity function for the Weibull distribution.
dwilcoxDensity function for the distribution of the Wilcoxonrank sum statistic.
ecdfComputes or plots an empirical cumulative distributionfunction.
eff.aovlistComputes the efficiencies of fixed-effects terms in ananalysis of variance model with multiple strata.
effectsReturns (orthogonal) effects from a fitted model, usually a linear model. This is a generic function, butcurrently only has a method for objects inheriting fromclasses `"lm"` and `"glm"`.
embedEmbeds the time series `x` into a low-dimensional Euclideanspace.
endExtracts and encodes the times the first and lastobservations were taken. Provided only for compatibility withS version 2.
estVarFunction to compute matrix of residual sums of squaresand products, or the estimated variance matrix formultivariate linear models.
expand.model.frameEvaluates new variables as if they had been part of theformula of the specified model. This ensures that the same`na.action` and `subset` arguments are applied andallows, for example, `x` tobe recovered for a model using `sin(x)` as a predictor.
extractAICComputes the (generalized) Akaike information criterionfor a fitted parametric model.
factanalPerforms maximum likelihood factor analysis on acovariance matrix or data matrix.
familyFamily objects provide a convenient way to specify thedetails of the models used by functions such as `glm`. See the documentation for`glm` for the details on howsuch model fitting takes place.
fftPerforms the fast Fourier transform of anarray.
filterApplies linear filtering to a univariate time series orto each series separately of a multivariate timeseries.
fisher.testPerforms Fisher's exact test for testing the null ofindependence of rows and columns in a contingency table withfixed marginals.
fitted, fitted.values`fitted` is a genericfunction that extracts fitted values from objects returned bymodeling functions. `fitted.values` is an alias forit.
fivenumReturns Tukey's five-number summary (minimum, lower-hinge, median, upper-hinge, maximum) for the inputdata.
fligner.testPerforms a Fligner-Killeen (median) test of the nullthat the variances in each of the groups (samples) are thesame.
formulaThe generic function `formula` and its specific methodsprovide a way of extracting formulas that have been includedin other objects.
frequencyReturns the number of samples per unit time from a`ts` object.
friedman.testPerforms a Friedman rank sum test with unreplicatedblocked data.
ftableCreates "flat" contingency tables.
gaussianFamily object for Gaussian functions (used by functionssuch as `glm`).
getInitialEvaluates initial parameter estimates for a nonlinearregression model.
get_all_varsReturns a data.frame containing the variables used informula plus those specified. Unlike `model.frame.default`, it returns theinput variables and not those resulting from function calls informula.
glmUsed to fit generalized linear models, specified bygiving a symbolic description of the linear predictor and adescription of the error distribution.
glm.controlAuxiliary function as user interface for `glm` fitting. Typically only usedwhen calling `glm` or`glm.fit`.
glm.fit`glm` is used to fitgeneralized linear models, specified by giving a symbolicdescription of the linear predictor and a description of theerror distribution.
hasTsp`tsp` returns the`tsp` attribute (or `NULL`). It is included forcompatibility with S version 2. `tsp<-` sets the `tsp` attribute. `hasTsp` ensures `x` has a `tsp` attribute, by adding one ifneeded.
hat, hatvalues, hatvalues.lmReturn the hat matrix for a model object (forregression diagnostics).
hclustHierarchical cluster analysis on a set ofdissimilarities and methods for analyzing it.
heatmapPlots a heat map object (an image with an accompanyingdendrogram).
influenceProvides the basic quantities that are used in forminga wide variety of diagnostics for checking the quality ofregression fits.
influence.measuresProduces a class "infl" object tabular display showingthe DFBETAS for each model variable, DFFITS, covarianceratios, Cook's distances, and the diagonal elements of the hatmatrix.
integrateAdaptive quadrature of functions of one variable over afinite or infinite interval.
interaction.plotPlots the mean (or other summary) of the response fortwo-way combinations of factors, thereby illustrating possibleinteractions.
inverse.gaussianFamily object for inverse Gaussian distributions (usedby functions such as `glm`).
is.empty.modelR model notation allows models with no intercept and nopredictors. These require special handling internally.`is.empty.model()` checkswhether an object describes an empty model.
is.leafClass `"dendrogram"`provides general functions for handling treelike structures.It is intended as a replacement for similar functions inhierarchical clustering and classification/regression trees, such that all of these can use the same engine for plotting orcutting trees. The code is still in the testing stage, and theAPI may change in the future.
is.mtsTells whether an object is of class `mts`.
is.stepfunTells whether an object is a function of class `stepfun`.
is.tsTells whether an object is of class `ts`.
is.tskernelTells whether an object is of class `tskernel`.
isoregComputes the isotonic (monotonically increasingnonparametric) least squares regression that is piecewiseconstant.
kernapplyComputes the convolution between an input sequence anda specific kernel.
kernelConstructs a general kernel or named specific kernels(returns a "tskernel" object).
kmeansPerforms k-means clustering on adata matrix.
knotsExtracts the knots from a step function (returned by`stepfun`).
kruskal.testPerforms a Kruskal-Wallis rank sum test.
ks.testPerforms one- or two-sample Kolmogorov-Smirnovtests.
lagComputes a lagged version of a time series, shiftingthe time base back by a given number of observations.
lag.plotPlots time series against lagged versions ofthemselves. Helps visualizing "autodependence" even whenautocorrelations vanish.
lineFits a line robustly.
lines.tsPlotting method for objects inheriting from class`"ts"`.
lm`lm` is used to fitlinear models. It can be used to carry out regression, single-stratum analysis of variance, and analysis ofcovariance (although `aov`may provide a more convenient interface for these).
lm.fitBasic computing engines called by `lm` and used to fit linear models.These should usually not be used directlyunless by experienced users.
lm.influenceProvides the basic quantities that are used in forminga wide variety of diagnostics for checking the quality ofregression fits.
lm.wfitBasic computing engines called by `lm` and used to fit linear models.These should usually not be used directlyunless by experienced users.
loessFits a polynomial surface determined by one or morenumerical predictors, using local fitting.
loess.controlSets control parameters for `loess` fits.
loess.smoothPlots and adds a smooth curve computed by `loess` to a scatter plot.
logLikExtracts the log-likelihood value from an object(usually a model).
loglinUsed to fit log-linear models to multidimensionalcontingency tables by iterative proportional fitting.
lowessPerforms the computations for locally weighted scatterplot smoothing (LOWESS), smoother which uses locally weightedpolynomial regression.
ls.diagComputes basic statistics, including standard errors, t-, and p-values, for the regression coefficients.
ls.printComputes basic statistics, including standard errors, t-, and p-values, for the regression coefficients and prints them if `print.it` is `TRUE`.
lsfitFinds the least squares estimate of β in the modelY = Xβ + ε.
madComputes the median absolute deviation, i.e., the(lo-/hi-) median of the absolute deviations from the medianand (by default) adjusts by a factor for asymptotically normalconsistency.
mahalanobisReturns the squared Mahalanobis distance of all rows in`x` and the vectorμ = `center` with respect to Σ= `cov`. This is(for vector `x`) defined asD2 = (x - μ)'Σ-1 (x - μ).
make.linkThis function is used with the `family` functions in `glm()`. Given the name of a link, itreturns a link function, an inverse link function, thederivative dμ / dη and a function fordomain checking.
makeARIMAUses Kalman filtering to find the (Gaussian)log-likelihood, or for forecasting or smoothing.
makepredictcallUtility to help `model.frame.default` create the rightmatrices when predicting from models with terms like `poly` or `ns`.
manovaA class for the multivariate analysis ofvariance.
mantelhaen.testPerforms a Cochran-Mantel-Haenszel chi-squared test ofthe null that two nominal variables are conditionallyindependent in each stratum, assuming that there is nothree-way interaction.
mauchly.testTests whether a Wishart-distributed covariance matrix(or transformation thereof) is proportional to a givenmatrix.
mcnemar.testPerforms McNemar's chi-squared test for symmetry ofrows and columns in a two-dimensional contingencytable.
medianComputes the sample median.
median.defaultComputes the sample median.
medpolishFits an additive model using Tukey's median polishprocedure.
model.extractReturns the response, offset, subset, weights, or otherspecial components of a model frame passed as optionalarguments to `model.frame`.
model.frame`model.frame` (ageneric function) and its methods return a `data.frame` with the variables neededto use `formula` and any`...` arguments.
model.matrixCreates a design matrix.
model.offsetReturns the offset of a model frame.
model.responseReturns the response of a model frame.
model.tablesComputes summary tables for model fits, especiallycomplex `aov` fits.
model.weightsReturns the weights of a model frame.
monthplotPlots seasonal (or other) subseries from a timeseries.
mood.testPerforms Mood's two-sample test for a difference inscale parameters.
mvfftPerforms the fast Fourier transform of anarray.
na.actionExtracts information on the NA action used to create anobject.
na.contiguousFinds the longest consecutive stretch of nonmissingvalues in a time series object. (In the event of a tie, thefirst such stretch.)
na.exclude`na.exclude` returnsthe object with incomplete cases removed and with the `na.action` attribute set to"exclude". (Usually used as an `na.action` argument for a modelingfunction.)
na.failReturns the object if it does not contain any missingvalues and signals an error otherwise. (Usually used as an`na.action` argument for amodeling function.)
na.omitReturns the object with incomplete cases removed.(Usually used as an `na.action` argument for a modelingfunction.)
na.passReturns an object unchanged. (Usually used as an`na.action` argument for amodeling function.)
napredictUses missing value information to adjust residuals andpredictions.
naprintUses missing value information to report the effects ofan `na.action`.
naresidUses missing value information to adjust residuals andpredictions.
nextnReturns the smallest integer, greater than or equal to`n`, that can be obtained asa product of powers of the values contained in `factors`.
nlmCarries out a minimization of the function `f` using a Newton-typealgorithm.
nlminbUnconstrained and constrained optimization using PORTroutines.
nlsDetermines the nonlinear (weighted) least squaresestimates of the parameters of a nonlinear model.
nls.controlAllows the user to set some characteristics of thenonlinear least squares algorithm.
numericDerivNumerically evaluates the gradient of anexpression.
offsetAn offset is a term to be added to a linear predictor, such as in a generalized linear model, with known coefficient1 rather than an estimated coefficient.
oneway.testTests whether two or more samples from normaldistributions have the same means. The variances are notnecessarily assumed to be equal.
optimGeneral-purpose optimization based on Nelder-Mead, quasi-Newton, and conjugate-gradient algorithms.It includes an option for box-constrained optimization andsimulated annealing.
optimise, optimizeThe function `optimize` searches the interval from`lower` to `upper` for a minimum or maximum ofthe function `f` with respectto its first argument. `optimise` is an alias for `optimize`.
order.dendrogramReturns the order (index) or the `"label"` attribute for the leaves ina dendrogram. These indices can then be used to access theappropriate components of any additional data.
pacfComputes partial autocorrelations.
pairwise.prop.testCalculates pairwise comparisons between pairs ofproportions with correction for multiple testing.
pairwise.t.testCalculates pairwise comparisons between group levelswith corrections for multiple testing.
pairwise.tableCreates a table of p-values forpairwise comparisons with corrections for multipletesting.
pairwise.wilcox.testCalculates pairwise comparisons between group levelswith corrections for multiple testing.
pbinomDistribution function for the binomialdistribution.
pbirthdayComputes the probability of a coincidence for ageneralized birthday paradox problem.
pcauchyDistribution function for the Cauchydistribution.
pchisqDistribution function for the chi-squareddistribution.
pexpDistribution function for the exponentialdistribution.
pfDistribution function for theF-distribution.
pgeomDistribution function for the geometricdistribution.
phyperDistribution function for the hypergeometricdistribution.
plclustHierarchical cluster analysis on a set ofdissimilarities and methods for analyzing it.
plnormDistribution function for the log-normaldistribution.
plogisDistribution function for the logisticdistribution.
plot.TukeyHSDCreates a set of confidence intervals on thedifferences between the means of the levels of a factor withthe specified family-wise probability of coverage. Theintervals are based on the Studentized range statistic, Tukey's honest significant difference method. There is a`plot` method.
plot.densityThe `plot` method fordensity objects.
plot.ecdfComputes or plots an empirical cumulative distributionfunction.
plot.lmPlots diagnostics for an lm object.
plot.mlmPlots diagnostics for an mlm object.
plot.spec, plot.spec.coherency, plot.spec.phasePlotting methods for objects of class `"spec"`. For multivariate timeseries, they plot the marginal spectra of the series or pairsplots of the coherency and phase of the cross-spectra.
plot.stepfunMethod of the generic `plot` for `stepfun` objects and utility forplotting piecewise-constant functions.
plot.tsPlotting method for objects inheriting from class`"ts"`.
pnbinomDistribution function for the negative binomialdistribution.
pnormDistribution function for the normaldistribution.
poissonFamily objects for Poisson distributions (used byfunctions such as `glm`).
poisson.testPerforms an exact test of a simple null hypothesisabout the rate parameter in a Poisson distribution or for theratio between two rate parameters.
poly, polymReturn or evaluate orthogonal polynomials of degree 1to `degree` over thespecified set of points `x`.These are all orthogonal to the constant polynomial of degree0. Alternatively, evaluate raw polynomials.
power.anova.testComputes power of test or determines parameters toobtain target power.
power.prop.testComputes power of test or determines parameters toobtain target power.
power.t.testComputes power of test or determines parameters toobtain target power.
ppointsGenerates the sequence of probability points `(1:m - a)/(m + (1-a)-a)`, where`m` is either `n`, if `length(n)==1`, or `length(n)`.
ppoisDistribution function for the Poissondistribution.
pprFits a projection pursuit regression model.
prcompPerforms a principal components analysis on the givendata matrix and returns the results as an object of class`prcomp`.
predictGeneric function for predictions from the results ofvarious model-fitting functions.
preplotComputes an object to be used for plots relating to thegiven model object.
princompPerforms a principal components analysis on the givennumeric data matrix and returns the results as an object ofclass `princomp`.
printCoefmatUtility function to be used in higher-level `print` methods, such as `print.summary.lm`, `print.summary.glm`, and `print.anova`. The goal is to providea flexible interface with smart defaults such that often only`x` needs to bespecified.
profileInvestigates the behavior of an objective function nearthe solution.
projReturns a matrix or list of matrices giving theprojections of the data onto the terms of a linear model. Itis most frequently used for `aov` models.
prop.testUsed for testing the null that the proportions(probabilities of success) in several groups are the same orthat they equal certain given values.
prop.trend.testPerforms a chi-squared test for trend in proportions, i.e., a test asymptotically optimal for local alternativeswhere the log odds vary in proportion with `score`. By default, `score` is chosen as the groupnumbers.
psignrankDistribution function for the distribution of theWilcoxon signed rank statistic.
ptDistribution function for thet-distribution.
ptukeyDistribution function for the Studentizedrange.
punifThese functions provide information about the uniformdistribution on the interval from `min` to `max`. `dunif` gives the density, `punif` gives the distributionfunction, `qunif` gives thequantile function, and `runif` generates randomdeviates.
pweibullDistribution function for the Weibulldistribution.
pwilcoxDistribution function for the distribution of theWilcoxon rank sum statistic.
qbetaQuantile function for the Beta distribution.
qbinomQuantile function for the binomialdistribution.
qbirthdayComputes the number of observations needed to have aspecified probability of coincidence for a generalizedbirthday paradox problem.
qcauchyQuantile function for the Cauchy distribution.
qchisqQuantile function for the chi-squareddistribution.
qexpQuantile function for the exponentialdistribution.
qfQuantile function for theF-distribution.
qgammaQuantile function for the Gamma distribution.
qgeomQuantile function for the geometricdistribution.
qhyperQuantile function for the hypergeometricdistribution.
qlnormQuantile function for the log-normaldistribution.
qlogisQuantile function for the logisticdistribution.
qnbinomQuantile function for the negative binomialdistribution.
qnormQuantile function for the normal distribution.
qpoisQuantile function for the Poisson distribution.
qqlineAdds a line to a normal Q-Q plot (usually generated byqqnorm or qqplot) that passes through the first and thirdquartiles.
qqnormGeneric function the default method of which produces anormal Q-Q plot of the values in `y`.
qqplotProduces a Q-Q plot of two data sets.
qsignrankDensity, distribution function, quantile function, andrandom generation for the distribution of the Wilcoxon signedrank statistic obtained from a sample with size `n`.
qtQuantile function for thet-distribution.
qtukeyFunction of the distribution of the Studentized range, R/s, where R is therange of a standard normal sample anddf∗s2 isindependently distributed as chi-squared withdf degrees of freedom; see `pchisq`.
quantileThe generic function `quantile` produces sample quantilescorresponding to the given probabilities. The smallestobservation corresponds to a probability of 0 and the largestto a probability of 1.
quantile.defaultThe generic function `quantile` produces sample quantilescorresponding to the given probabilities. The smallestobservation corresponds to a probability of 0 and the largestto a probability of 1.
quasiFamily object for the quasi distribution (used byfunctions such as `glm`).
quasibinomialFamily object for the quasibinomial distribution (usedby functions such as `glm`).
quasipoissonFamily object for the quasi-Poisson distribution (usedby functions such as `glm`).
qunifQuantile function for the uniform distribution.
qweibullQuantile function for the Weibull distribution.
qwilcoxQuantile function for the Wilcoxon rank sumstatistic.
r2dtableGenerates random two-way tables with given marginalsusing Patefield's algorithm.
rbetaRandom number generation for the Betadistribution.
rbinomRandom number generation for the binomialdistribution.
rcauchyRandom number generation for the Cauchydistribution.
rchisqRandom number generation for the chi-squareddistribution.
rect.hclustDraws rectangles around the branches of a dendrogram, highlighting the corresponding clusters. First, the dendrogramis cut at a certain level, and then a rectangle is drawnaround selected branches.
reformulateCreates a formula from a character vector.
relevelThe levels of a factor are reordered so that the levelspecified by `ref` is first, and the others are moved down. This is useful for `contr.treatment` contrasts, whichtake the first level as the reference.
reorder`reorder` is a genericfunction. Its `"factor"`method reorders the levels of a factor depending on values ofa second variable, usually numeric. The `"character"` method is a convenientalias.
replicationsReturns a vector or a list of the number of replicatesfor each term in the formula.
reshapeReshapes a data frame between "wide" format withrepeated measurements in separate columns of the same recordand "long" format with the repeated measurements in separaterecords.
residGeneric function that extracts model residuals fromobjects returned by modeling functions. The abbreviated form`resid` is an alias for`residuals`.
residualsGeneric function that extracts model residuals fromobjects returned by modeling functions.
rexpRandom generation for the exponentialdistribution.
rfRandom generation for theF-distribution.
rgammaRandom generation for the Gamma distribution.
rgeomRandom generation for the geometricdistribution.
rhyperRandom generation for the hypergeometricdistribution.
rlnormRandom generation for the log-normaldistribution.
rlogisRandom generation for the logisticdistribution.
rmultinomGenerates multinomially distributed random numbervectors and computes multinomialprobabilities.
rnbinomRandom generation for the negative binomialdistribution.
rnormRandom generation for the normal distribution.
rpoisRandom generation for the Poisson distribution.
rsignrankRandom generation for the distribution of the Wilcoxonsigned rank statistic.
rstandardReturns the standardized residuals from a modelobject.
rstudentReturns the Studentized residuals from a modelobject.
rtRandom generation for thet-distribution.
runifGenerates random numbers from the uniformdistribution.
runmedComputes running medians of odd span. This is the "mostrobust" scatter plot smoothing possible. For efficiency (andhistorical reasons), you can use one of two differentalgorithms giving identical results.
rweibullRandom generation for the Weibull distribution.
rwilcoxRandom generation for the distribution of the Wilcoxonrank sum statistic.
scatter.smoothPlots and adds a smooth curve computed by `loess` to a scatter plot.
screeplotPlots the variances against the number of the principalcomponent. This is also the `plot` method for classes `"princomp"` and `"prcomp"`.
sdComputes the standard deviation of the values in`x`.
se.contrastReturns the standard errors for one or more contrastsin an `aov` object.
selfStartConstructs self-starting nonlinear models.
setNamesThis is a convenience function that sets the names onan object and returns the object. It is most useful at the endof a function definition where one is creating the object to be returned andwould prefer not to store it under a name just so the namescan be assigned.
shapiro.testPerforms the Shapiro-Wilk test of normality.
simulateSimulates one or more responses from the distributioncorresponding to a fitted model object.
smoothTukey's smoothers, 3RS3R, 3RSS, 3R, etc.
smooth.splineFits a cubic smoothing spline to the supplieddata.
smoothEndsSmooths end points of a vector `y` using subsequently smaller mediansand Tukey's end point rule at the very end.
sortedXyDataThis is a constructor function for the class of`sortedXyData` objects. Theseobjects are mostly usedin the `initial` function fora self-starting nonlinear regression model, which will be ofthe `selfStart` class.
spec.arFits an AR model to `x` (or uses the existing fit) andcomputes (and by default plots) the spectral density of thefitted model.
spec.pgramCalculates the periodogram using a fast Fouriertransform and optionally smooths the result with a series ofmodified Daniell smoothers (moving averages giving half weightto the end values).
spec.taperApplies a cosine-bell taper to a time series.
spectrumEstimates the spectral density of a timeseries.
splinePerforms cubic spline interpolation of given datapoints, returning either a list of points obtained by theinterpolation or a function performingthe interpolation. Returns a list containing components`x` and `y`, which give the ordinates whereinterpolation took place and the interpolated values.
splinefunPerforms cubic spline interpolation of given datapoints, returning either a list of points obtained by theinterpolation or a function performingthe interpolation. Returns a function with formal arguments`x` and `deriv`, the latter defaulting to0.
splinefunHPerforms Hermite spline interpolation of given datapoints, returning either a list of points obtained by theinterpolation or a function performingthe interpolation.
startExtracts and encodes the times the first and lastobservations were taken. Provided only for compatibility withS version 2.
stat.anovaUtility function, used in `lm` and `glm` methods for `anova(..., test != NULL)` and shouldnot be used by the average user.
stepSelects a formula-based model by AIC.
stepfunReturns an interpolating step function from two sets ofvectors.
stlDecomposes a time series into seasonal, trend, andirregular components using `loess`.
supsmuSmooths the (x, y) values by Friedman'ssupersmoother.
symnumSymbolically encodes a given numeric or logical vectoror array. Particularly useful for visualization of structuredmatrices, e.g., correlation, sparse, or logical ones.
t.testPerforms one- and two-samplet-tests on vectors of data.
termplotPlots regression terms against their predictors, optionally with standard errors and partial residualsadded.
termsGeneric function that can be used to extractterms objects from various kinds of Rdata objects.
timeCreates the vector of times at which a time series wassampled.
toeplitzForms a symmetric Toeplitz matrix given its firstrow.
tsUsed to create time series objects.
ts.intersectBinds time series that have a common frequency.`ts.intersect` is restrictedto the time covered by all the series.
ts.plotPlots several time series on a common plot. Unlike`plot.ts`, the series canhave different time bases, but they should have the samefrequency.
ts.unionBinds time series that have a common frequency.`ts.union` pads with `NA`s to the total timecoverage.
tsSmoothPerforms fixed-interval smoothing on a univariate timeseries via a state-space model.
tsdiagGeneric function to plot time seriesdiagnostics.
tsp, tsp<-`tsp` returns the`tsp` attribute (or `NULL`). It is included forcompatibility with S version 2. `tsp<-` sets the `tsp` attribute.
unirootSearches the interval from `lower` to `upper` for a root (i.e., 0) of thefunction `f` with respect toits first argument.
updateUpdates and (by default) refits a model. It does thisby extracting the call stored in the object, updating the calland (by default) evaluating that call.
varComputes the variance of a vector.
var.testPerforms an F-test to compare thevariances of two samples from normal populations.
variable.namesSimple utility returning (nonmissing) case names and(noneliminated) variable names.
vcovReturns the variance-covariance matrix of the mainparameters of a fitted model object.
weighted.meanComputes a weighted mean of a numeric vector.
weighted.residualsComputes weighted residuals from a linear modelfit.
weightsAll these functions are `methods` for class `"lm"` objects.
wilcox.testPerforms one- and two-sample Wilcoxon tests on vectorsof data; the latter is also known as the Mann-Whitneytest.
window, window<-`window` is a genericfunction that extracts the subset of the object `x` observed between the times`start` and `end`. If a frequency is specified, the series is then resampled at the new frequency.
write.ftableReads, writes, and coerces "flat" contingencytables.
xtabsCreates a contingency table from cross-classifyingfactors, usually contained in a data frame, using a formulainterface.

### Data Set

Data SetClassDescription
p.adjust.methodscharacterAllowed methods for `p.adjust`.

## stats4

This package contains statistical functions using S4methods and classes.

### Functions

FunctionDescription
AICCalculates the Akaike information criterion for one orseveral fitted model objects for which a log-likelihood valuecan be obtained.
BICCalculates the Bayesian information criterion (BIC), also known as Schwarz's Bayesian criterion (SBC), for one orseveral fitted model objects for which a log-likelihood valuecan be obtained, according to the formula −2 ∗ log-likelihood+ npar ∗log(nobs), wherenpar representsthe number of parameters andnobs the number ofobservations in the fitted model.
coefExtracts model coefficients from objects returned bymodeling functions.
confintComputes confidence intervals for one or moreparameters in a fitted model.
logLikExtracts the log-likelihood from a modelobject.
mleEstimates parameters by the method of maximumlikelihood.
plotGeneric function for plotting an R object.
profileInvestigates behavior of objective function near thesolution represented by fitted.
summaryGeneric function used to produce result summaries ofthe results of various model-fitting functions.
updateUpdates and (by default) refits a model.
vcovReturns the variance-covariance matrix of the mainparameters of a fitted model object.

## survival

This package contains functions for survivalanalysis.

### Functions

FunctionDescription
SurvCreates a survival object, usually used as a responsevariable in a model formula.
aaregReturns an object of class `"aareg"` that represents an Aalenmodel.
attrassignThe `"assign"`attribute on model matrices describes which columns come fromwhich terms in the model formula.
basehazComputes the baseline survival curve for a Coxmodel.
cchReturns estimates and standard errors from relativerisk regression fit to data from case-cohort studies, cohortdata, and Borgan II, a generalization of the Lin-Yingestimator.
clogitEstimates a logistic regression model by maximizing theconditional likelihood.
clusterThis is a special function used in the context ofsurvival models. It identifies correlated groups ofobservations and is used on the righthand side of aformula.
cox.zphTests the proportional hazards assumption for a Coxregression model fit (`coxph`).
coxphFits a Cox proportional hazards regressionmodel.
coxph.controlUsed to set various numeric parameters controlling aCox model fit. Typically, it would only be used in a call to`coxph`.
coxph.detailReturns the individual contributions to the first andsecond derivative matrix, at each unique event time.
coxph.fitInternal survival function.
dsurvregDensity, cumulative probability, and quantiles for theset of distributions supported by the `survreg` function.
format.SurvCreates a survival object, usually used as a responsevariable in a model formula.
frailtyAdds a simple random-effects term to a Cox or survregmodel.
is.SurvTests for a survival object.
is.na.SurvTests for NA values in a survival object.
is.na.ratetableMatches variable names in data to those in a rate tablefor `survexp`.
is.ratetableVerifies not only the `class` attribute but also thestructure of the object.
labels.survregFinds a suitable set of labels from a survival objectfor use in printing or plotting, for example.
psplineSpecifies a penalized spline basis for thepredictor.
psurvregDensity, cumulative probability, and quantiles for theset of distributions supported by the `survreg` function.
pyearsComputes the person-years of follow-up time contributedby a cohort of subjects, stratified into subgroups.
qsurvregDensity, cumulative probability, and quantiles for theset of distributions supported by the `survreg` function.
ratetableMatches variable names in data to those in a rate tablefor `survexp`.
ridgeSpecifies a ridge regression term when used in a coxphor survreg model formula.
strataThis is a special function used in the context of theCox survival model. It identifies stratification variableswhen they appear on the righthand side of a formula.
survConcordanceComputes the concordance between a right-censoredsurvival time and a single continuous covariate.
survSplitGiven a survival data set and a set of specified cuttimes, splits each record into multiple subrecords at each cuttime. The new data set will be in "counting process" format, with a start time, stop time, and event status for eachrecord.
survdiffTests if there is a difference between two or moresurvival curves using theGρ family oftests, or for a single curve against a knownalternative.
survexpReturns either the expected survival of a cohort ofsubjects or the individual expected survival for eachsubject.
survfitComputes an estimate of a survival curve for censoreddata using either the Kaplan-Meier or the Fleming-Harringtonmethod or computes the predicted survivor function.
survobrienO'Brien's test for association of a single variablewith survival.
survregFits a parametric survival regression model. These arelocation-scale models for an arbitrary transform of the timevariable; the most common cases use a log transformation, leading to accelerated failure time models.
survreg.controlChecks and packages the fitting options for `survreg`.
survreg.fitInternal survival function.
survregDtestThis routine is called by `survreg` to verify that adistribution object is valid.
tcutAttaches categories for person-year calculations to avariable without losing the underlying continuousrepresentation.
untangle.specialsGiven a `terms`structure and a desired special name, this returns an indexappropriate for subscripting the `terms` structure and anotherappropriate for the data frame.

### Data Sets

Data SetClassDescription
amldata.frameSurvival in patients with acute myelogenousleukemia. The question at the time was whether the standardcourse of chemotherapy should be extended ("maintenance") foradditional cycles.
bladderdata.frameData on recurrences of bladder cancer, used by manypeople to demonstrate methodology for recurrent eventmodeling. Bladder1 is the full data set from the study. Thisdata set contains only the 85 subjects with nonzero follow-upwho were assigned to either thiotepa or placebo.
bladder1data.frameData on recurrences of bladder cancer, used by manypeople to demonstrate methodology for recurrent eventmodeling. Bladder1 is the full data set from the study. Itcontains all three treatment arms and all recurrences for 118subjects; the maximum observed number of recurrences is9.
bladder2data.frameData on recurrences of bladder cancer, used by manypeople to demonstrate methodology for recurrent eventmodeling. Bladder2 uses the same subset of subjects asbladder, but formatted in the (start, stop] or Anderson-Gillstyle.
cancerdata.frameSurvival in patients with advanced lung cancer from theNorth Central Cancer Treatment Group. Performance scores ratehow well the patient can perform normal dailyactivities.
cgddata.frameData is from a placebo controlled trial of gammainterferon in chronic granulotomous disease (CGD).
colondata.frameData from one of the first successful trials ofadjuvant chemotherapy for colon cancer.
heart, jasa, jasa1data.frameSurvival of patients on the waiting list for theStanford heart transplant program.
kidneydata.frameData on the recurrence times to infection, at the pointof insertion of the catheter, for kidney patients usingportable dialysis equipment.
leukemiadata.frameSurvival in patients with acute myelogenous leukemia.The question at the time was whether the standard course ofchemotherapy should be extended ("maintenance") for additionalcycles.
lungdata.frameSurvival in patients with advanced lung cancer from theNorth Central Cancer Treatment Group. Performance scores ratehow well the patient can perform normal dailyactivities.
mgus, mgus1, mgus2data.frameNatural history of 241 subjects with monoclonalgammapathy of undetermined significance (MGUS).
nwtcodata.frameMissing data/measurement error example. Tumor histologypredicts survival, but prediction is stronger with central labhistology than with the local institutiondetermination.
ovariandata.frameSurvival in a randomized trial comparing two treatmentsfor ovarian cancer.
pbcdata.frameThis data is from the Mayo Clinic trial in primarybiliary cirrhosis (PBC) of the liver conducted between 1974and 1984.
pbcseqdata.frameThis data is a continuation of the PBC data set andcontains the follow-up laboratory data for each studypatient.
ratsdata.frameForty-eight rats were injected with a carcinogen andthen randomized to either drug or placebo. The number oftumors ranged from 0 to 13; all rats were censored at 6 months afterrandomization.
stanford2data.frameThis contains the Stanford heart transplant data in adifferent format. The main data set is in `heart`.
survexp.mnratetableCensus data sets for the expected-survival andperson-year functions.
survexp.mnwhiteratetableCensus data sets for the expected-survival andperson-year functions.
survexp.usratetableCensus data sets for the expected-survival andperson-year functions.
survexp.usrratetableCensus data sets for the expected-survival andperson-year functions.
survreg.distributionslistList of distributions for accelerated failure models.These are location-scale families for some transformation oftime.
tobindata.frameEconomists fit a parametric censored data model calledthe tobit. The data come from Tobin'soriginal paper.
veterandata.frameRandomized trial of two treatment regimens for lungcancer. This is a standard survival analysis data set.

## tcltk

The package contains interface and language bindings toTcl/Tk GUI elements. Please see the online help for more details.

## tools

This package provides tools for developingpackages.

### Functions

FunctionDescription
Rd2HTMLThis (experimental) function converts from an R helppage to an HTML document.
Rd2exThis (experimental) function converts from an R helppage to the format used by example.
Rd2latexThis (experimental) function converts from an R helppage to a LaTeX document.
Rd2txtThis (experimental) function converts from an R helppage to a text document.
Rd_dbBuilds a simple database of all R documentation (Rd)sources in a package, as a list of character vectors with thelines of the Rd files in the package.
RdiffGiven two R output files, computes differences, ignoring headers, footers, and some encodingdifferences.
RdindexPrints a two-column index table with names and titlesfrom given R documentation files to a given output file orconnection. The titles are nicely formatted between two columnpositions (typically 25 and 72, respectively).
buildVignettesRuns `Sweave` and`texi2dvi` on all vignettesof a package.
checkDocFilesChecks, for all Rd files in a package, whether allarguments shown in the usage sections of the Rd file aredocumented in its arguments section.
checkDocStyleInvestigates how (S3) methods are shown in the usagesof the Rd files in a package.
checkFFPerforms checks on calls to compiled code from Rcode.
checkMD5sumsChecks the files against a file "MD5".
checkNEWSReads R's NEWS file or a similarly formatted one. Thisis an experimental feature, new in R 2.4.0, and may change inseveral ways.
checkRdThese experimental functions take the output of the`parse_Rd` function and checkit or produce a help page from it. Their interfaces (andexistence!) are subject to change.
checkReplaceFunsChecks whether replacement functions or S3/S4replacement methods in the package R code have their finalargument named value.
checkS3methodsChecks whether all S3 methods defined in the package Rcode have all arguments of the corresponding generic, withpositional arguments of the generics in the same positions forthe method.
checkTnFChecks the specified R package or code file foroccurrences of `T` or`F` and gathers theexpressions containing these.
checkVignettesChecks all `Sweave`files of a package by running `Sweave` and/or `Stangle` on them.
codocCompares names and optionally also correspondingpositions and default values of the arguments offunctions.
codocClassesFinds inconsistencies between actual and documented"structure" of R objects in a package. `codoc` compares names and optionallyalso corresponding positions and default values of thearguments of functions. `codocClasses` and `codocData` compare slot names of S4classes and variable names of data sets, respectively.
codocDataCompares slot names of S4 classes.
delimMatchMatches delimited substrings in a character vector, with proper nesting.
dependsOnPkgsFinds "reverse" dependencies of packages, i.e., thosepackages that depend on this one and (optionally) so onrecursively.
encoded_text_to_latexTranslates non-ASCII characters in text to LaTeX escapesequences.
file_path_as_absoluteTurns a possibly relative file path absolute, performing tilde expansion, if necessary.
file_path_sans_extReturns the file paths without extension.
getDepListGiven a dependency matrix, creates a `DependsList` object for that package, which will include the dependencies for that matrix, whichones are installed, which unresolved dependencies were foundonline, which unresolved dependencies were not found online, and any R dependencies.
installFoundDependsTakes the `Found`element of a `pkgDependsList`object and attempts to install all of the listed packages fromthe specified repositories.
list_files_with_extsReturns the paths or names of the files in directorydir with extensions matching one of the elements ofexts.
list_files_with_typeReturns the paths of the files in dir of the given"type, " as determined by the extensions recognized byR.
md5sumComputes the 32-byte MD5 checksums of one or morefiles.
package.dependenciesParses and checks the dependencies of a package againstthe currently installed version of R (and otherpackages).
parse_RdReads an Rd file and parses it, for processing by otherfunctions. It is experimental.
pkgDependsConvenience function that wraps getDepList and takes asinput a package name.
pkgVignettesRuns `Sweave` and`texi2dvi` on all vignettesof a package.
readNEWSRead R's NEWS file or a similarly formatted one. Thisis an experimental feature, new in R 2.4.0, and may change inseveral ways.
showNonASCIIPrints elements of a character vector that containnon-ASCII bytes, printing such bytes as an escape like`<fc>`.
testInstalledBasicAllows an installed package to be tested by running thebasic tests.
testInstalledPackageAllows an installed package to be tested.
testInstalledPackagesAllows all base and recommended packages to betested.
texi2dviRuns `latex` and`bibtex` until allcross-references are resolved and creates either a deviceindependent (DVI) or a PDF file.
undocFinds the objects in a package that are undocumented, in the sense that they are visible to the user (or dataobjects or S4 classes provided by the package), but nodocumentation entry exists.
vignetteDependsGiven a vignette name, creates a DependsList objectthat reports information about the packages the vignettedepends on.
write_PACKAGESGenerates `PACKAGES`and `PACKAGES.gz` files for arepository of source or Mac/Windows binary packages.
xgettext, xgettext2pot, xngettextFor each file in the `R` directory (includingsystem-specific subdirectories) of a package, extract theunique arguments passed to `stop`, `warning`, `message`, `gettext`, and `gettextf`, or to `ngettext`.

### Data Sets

Data SetClassDescription
charset_to_UnicodehexmodeA matrix of Unicode points with columns for the common8-bit encodings.

## utils

This package contains a variety of utility functions forR, including package management, file reading and writing, andediting.

### Functions

FunctionDescription
?Documentation on a topic.
RShowDocUtility function to find and display Rdocumentation.
RSiteSearchSearches for keywords or phrases in the R-help mailinglist archives, help pages, vignettes, or task views, using thesearch engine at http://search.r-project.org, and displays theresults in a web browser.
RprofEnables or disables profiling of the execution of Rexpressions.
RprofmemEnables or disables reporting of memory allocation inR.
RtangleA driver for `Stangle`that extracts R code chunks.
RtangleSetupA driver for `Stangle`that extracts R code chunks.
RtangleWritedocThese functions are handy for writing Sweave driversand currently not documented. Look at the source code of theSweave Latex driver (in this package) or the HTML driver (inthe R2HTML package from CRAN) to see how they can beused.
RweaveChunkPrefixThese functions are handy for writing Sweave driversand currently not documented. Look at the source code of theSweave Latex driver (in this package) or the HTML driver (inthe R2HTML package from CRAN) to see how they can beused.
RweaveEvalWithOptThese functions are handy for writing Sweave driversand currently not documented. Look at the source code of theSweave Latex driver (in this package) or the HTML driver (inthe R2HTML package from CRAN) to see how they can beused.
RweaveLatexA driver for `Sweave`that translates R code chunks in LaTeX files.
RweaveLatexFinishThese functions are handy for writing Sweave driversand currently not documented. Look at the source code of theSweave Latex driver (in this package) or the HTML driver (inthe R2HTML package from CRAN) to see how they can beused.
RweaveLatexOptionsThese functions are handy for writing Sweave driversand currently not documented. Look at the source code of theSweave Latex driver (in this package) or the HTML driver (inthe R2HTML package from CRAN) to see how they can beused.
RweaveLatexSetupA driver for `Sweave`that translates R code chunks in LaTeX files.
RweaveLatexWritedocThese functions are handy for writing Sweave driversand currently not documented. Look at the source code of theSweave Latex driver (in this package) or the HTML driver (inthe R2HTML package from CRAN) to see how they can beused.
RweaveTryStopThese functions are handy for writing Sweave driversand currently not documented. Look at the source code of theSweave Latex driver (in this package) or the HTML driver (inthe R2HTML package from CRAN) to see how they can beused.
StangleA frontend to `Sweave`using a simple driver by default, which discards thedocumentation and concatenates all code chunks the current Sengine understands.
Sweave`Sweave` provides aflexible framework for mixing text and S code for automaticreport generation. The basic idea is to replace the S codewith its output, such that the final document only containsthe text and the output of the statistical analysis.
SweaveSyntConvThis function converts the syntax of files in `Sweave` format to another Sweavesyntax definition.
URLdecodeFunction to decode characters in URLs.
URLencodeFunction to encode characters in URLs.
ViewInvokes a spreadsheet-style data viewer on amatrix-like R object.
alarmGives an audible or visual signal to the user.
apropos`apropos()` returns acharacter vector giving the names of all objects in the searchlist matching a specified value.
argsAnywhereReturns the arguments for all functions with a namematching its argument, whether visible on the search path, registered as an S3 method, or in a namespace but notexported.
as.personA class and utility method for holding informationabout persons such as name and email address.
as.personListA class and utility method for holding informationabout persons such as name and email address.
as.relistable`relist()` is an S3generic function with a few methods in order to allow easyinversion of `unlist(obj)`when that is used with an object of (S3) class `"relistable"`.
as.romanManipulates integers as roman numerals.
assignInNamespaceUtility function to access and replace the nonexportedfunctions in a namespace, for use in developing packages withnamespaces.
available.packagesUsed to automatically compare the version numbers ofinstalled packages with the newest available version on therepositories and update outdated packages on the fly.
browseEnvOpens a browser with list of objects currently in the`sys.frame()`environment.
browseURLLoads a given URL into a web browser.
browseVignettesLists available vignettes in an HTML browser with linksto PDF, LaTeX/noweb source, and (tangled) R code (ifavailable).
bug.reportInvokes an editor to write a bug report and optionallymail it to the automated r-bugs repository atr-bugs@r-project.org. Some standardinformation on the current version and configuration of R areincluded automatically.
capture.outputEvaluates its arguments with the output being returnedas a character string or sent to a file. Related to `sink` in the same way that `with` is related to `attach`.
checkCRANFunctions helping to maintain CRAN, some of which mayalso be useful to administrators of other repositorynetworks.
chooseCRANmirrorInteracts with the user to choose a CRANmirror.
citEntryCreates "citation" objects, which are modeled afterBibTeX entries.
citFooterCreates a footer in a CITATION file.
citationShows how to cite R and R packages inpublications.
close.socketCloses the socket and frees the space in the filedescriptor table. The port may not be freedimmediately.
combnGenerates all combinations of the elements of `x` taken `m` at a time. If `x` is a positive integer, returns allcombinations of the elements of `seq(x)` taken `m` at a time. If argument `FUN` is not `NULL`, applies a function given bythe argument to each point. If simplify is FALSE, returns alist; otherwise, returns an `array`, typically a `matrix`. `...` are passed unchanged to the`FUN` function, ifspecified.
compareVersionCompares two package version numbers to see which islater.
contrib.urlUsed to automatically compare the version numbers ofinstalled packages with the newest available version on therepositories and update outdated packages on the fly.
count.fieldsCounts the number of fields, as separated by `sep`, in each of the lines of`file` read.
dataLoads specified data sets or lists the available datasets.
data.entry, dataentry, de, de.ncols, de.restore, de.setupSpreadsheet-like editors for entering or editingdata.
debuggerFunction to dump the evaluation environments (frames)and to examine dumpedframes.
demoUser-friendly interface for running some demonstrationR scripts. `demo()` gives thelist of available topics.
download.packagesUsed to automatically compare the version numbers ofinstalled packages with the newest available version on therepositories and update outdated packages on the fly.
dump.framesFunction to dump the evaluation environments (frames)and to examine dumpedframes.
editInvokes an editor on an R object.
emacsInvokes the text editor emacs on an R object.
exampleRuns all the R code from theExamples part of R's online help.
file.editEdits one or more files in a text editor.
file_testUtility for shell-style file tests.
findReturns a character vector giving the names of allobjects in the search list matching a given value.
fixInvokes `edit` on`x` and assigns the new(edited) version of `x` inthe user's workspace.
fixInNamespaceUtility function to access and replace the nonexportedfunctions in a namespace, for use in developing packages withnamespaces.
flush.consoleOn the Mac OS X and Windows GUIs, ensures that thedisplay of output in the console is current, even if outputbuffering is on. (This does nothing except on console-basedversions of R.)
formatOL, formatULFormat unordered (itemize) and ordered (enumerate)lists.
getAnywhereLocates and returns all objects with a name matchingits argument, whether visible on the search path, registeredas an S3 method, or in a namespace but not exported.
getCRANmirrorsInteracts with the user to choose a CRANmirror.
getFromNamespaceUtility function to access and replace the nonexportedfunctions in a namespace, for use in developing packages withnamespaces.
getS3methodGets a method for an S3 generic, possibly from anamespace.
getTxtProgressBarText progress bar in the R console.
glob2rxChanges wildcard (akaglobbing) patterns into the correspondingregular expressions (`regexp`).
headReturns the first or last parts of a vector, matrix, table, data frame, or function. Since `head()` and `tail()` are generic functions, theymay also have been extended to other classes.
helpThe primary interface to R's help system.
help.requestPrompts users to check they have done all that isexpected of them before sending a post to the R-help mailinglist, provides a template for the post with sessioninformation included, and optionally sends the email (on Unixsystems).
help.searchAllows for searching the help system for documentationmatching a given character string in the (file) name, alias, title, concept, or keyword entries (or any combinationthereof), using either fuzzy matching or regular expressionmatching. Names and titles of the matched help entries aredisplayed nicely formatted.
help.startStarts the hypertext (currently HTML) version of R'sonline documentation.
historyLoads or saves or displays the commandshistory.
index.searchUsed to search the indexes for help files, possiblyunder aliases.
install.packagesUsed to automatically compare version numbers ofinstalled packages with the newest available version on therepositories and update outdated packages on the fly.
installed.packagesFinds (or retrieves) details of all packages installedin the specified libraries.
is.relistable`relist()` is an S3generic function with a few methods in order to allow easyinversion of `unlist(obj)`when that is used with an object of (S3) class `"relistable"`.
limitedLabelsAllows the user to browse directly on any of thecurrently active function calls and is suitable as an erroroption. The expression `options(error=recover)` will makethis the error option.
localeToCharsetAims to find a suitable coding for the locale named, bydefault the current locale, and if it is a UTF-8 locale, asuitable single-byte encoding.
ls.str, lsf.str`ls.str` and `lsf.str` are variations of `ls` applying `str()` to each matched name.
make.socketWith `server = FALSE`, attempts to open a client socket to the specified port andhost. With `server = TRUE`, listens on the specified port for a connection and thenreturns a server socket. It is a good idea to use `on.exit` to ensure that a socket isclosed, as you only get 64 of them.
makeRweaveLatexCodeRunnerThese functions are handy for writing Sweave driversand currently not documented. Look at the source code of theSweave Latex driver (in this package) or the HTML driver (inthe R2HTML package from CRAN) to see how they can beused.
memory.limitGets or sets the memory limit on Microsoft Windowsplatforms.
memory.sizeChecks the current memory usage on Microsoft Windowsplatforms.
menuPresents the user with a menu of choices labeled from 1to the number of choices. To exit without choosing an item, select 0.
methodsLists all available methods for an S3 generic functionor all methods for a class.
mirror2htmlFunctions helping to maintain CRAN, some of which mayalso be useful to administrators of other repositorynetworks.
modifyListModifies a possibly nested list recursively by changinga subset of elements at each level to match a secondlist.
new.packagesUsed to automatically compare the version numbers ofinstalled packages with the newest available version on therepositories and update outdated packages on the fly.
normalizePathConverts file paths to canonical form for the platform, to display them in a user-understandable form.
nslInterface to gethostbyname.
object.sizeProvides an estimate of the memory that is being usedto store an R object.
old.packagesUsed to automatically compare the version numbers ofinstalled packages with the newest available version on therepositories and update outdated packages on the fly.
package.skeletonAutomates some of the setup for a new source package.It creates directories; saves functions, data, and R codefiles to appropriate places; and creates skeleton help filesand a `Read-and-delete-me`file describing further steps in packaging.
packageDescriptionParses and returns the `DESCRIPTION` file of apackage.
packageStatusSummarizes information about installed packages andpackages available at various repositories, and automaticallyupgrades outdated packages.
pageDisplays a representation of the object named by`x` in a pager via `file.show`.
personCreates a "person" object.
personListCreates a "personList" object.
picoInvokes a text editor on an R object.
promptFacilitates the construction of files documenting Robjects.
promptDataGenerates a shell of documentation for a dataset.
promptPackageGenerates a shell of documentation for an installed orsource package.
read.DIFReads a file in Data Interchange Format (DIF) andcreates a data frame from it. DIF is a format for datamatrices such as single spreadsheets.
read.fwfReads a table of fixed-width-formatted data into a`data.frame`.
read.socket`read.socket` reads astring from the specified socket; `write.socket` writes to the specifiedsocket. There is very little error checking done byeither.
read.tableReads a file in table format and creates a data framefrom it, with cases corresponding to lines and variables tofields in the file.
readCitationFileThe `CITATION` fileof R packages contains an annotated list of references thatshould be used for citing the packages.
recoverAllows the user to browse directly on any of thecurrently active function calls and is suitable as an erroroption. The expression `options(error=recover)` will makethis the error option.
relist`relist()` is an S3generic function with a few methods in order to allow easyinversion of `unlist(obj)`when that is used with an object of (S3) class `"relistable"`.
remove.packagesRemoves installed packages/bundles and updates indexinformation as necessary.
rtagsProvides etags-like indexing capabilities for R code, using R's own parser.
savehistoryLoads or saves or displays the commandshistory.
select.listSelects item(s) from a character vector.
setRepositoriesInteracts with the user to choose the packagerepositories to be used.
setTxtProgressBarText progress bar in the R console.
stackStacking vectors concatenates multiple vectors into asingle vector along with a factor indicating where eachobservation originated; unstacking reverses this.
strCompactly displays the internal structure of an Robject; the idea is to give reasonable output forany R object.
strOptions`strOptions()` is aconvenience function for setting `options(str = .)`.
summaryRprofSummarizes the output of the `Rprof` function to show the amount oftime used by different R functions.
tailReturns the first or last parts of a vector, matrix, table, data frame, or function. Since `head()` and `tail()` are generic functions, theymay also have been extended to other classes.
timestampLoads or saves or displays the commandshistory.
toBibtexConverts R objects to character vectors with BibTeXmarkup.
toLatexConverts R objects to character vectors with LaTeXmarkup.
txtProgressBarText progress bar in the R console.
type.convertConverts a character vector to logical, integer, numeric, complex, or factor, as appropriate.
unstackStacking vectors concatenates multiple vectors into asingle vector along with a factor indicating where eachobservation originated; unstacking reverses this.
unzipExtracts files from or lists a zip archive.
update.packageStatusSummarizes information about installed packages andpackages available at various repositories and automaticallyupgrades outdated packages.
update.packagesUsed to automatically compare the version numbers ofinstalled packages with the newest available version on therepositories and update outdated packages on the fly.
url.showExtension of `file.show` to display text files froma remote server.
viInvokes a text editor on an R object.
vignetteViews a specified vignette or lists the availableones.
write.csv, write.csv2Convenience wrappers to `write.table` for producing CSV filesfrom an R object.
write.socket`read.socket` reads astring from the specified socket; `write.socket` writes to the specifiedsocket. There is very little error checking done byeither.
write.tablePrints its required argument `x` (after converting it to a dataframe if it is not one nor a matrix) to a file orconnection.
wsbrowserThe `browseEnv`function opens a browser with list of objects currently in the`sys.frame()`environment.
xeditInvokes the xedit editor on an R object.
xemacsInvokes the xemacs editor on an R object.
zip.file.extractExtracts the file named `file` from the zip archive, ifpossible, and writes it in a temporary location.