Data mining and visualization

Data mining and visualization [R logo]

auto.aspect | Choose aspect ratio
bhist | Histogram with confidence intervals
boxplot.hclust | Boxplot with hierarchical cluster breaks
BrBg.colors | Color schemes
break.hclust | Quantize by clustering
break.kmeans | Quantize by clustering
break.quantile | Equal-count breaks of a dataset
break.ts | Change-point analysis by clustering
break.ward | Quantize by clustering
Cars | Cars, Housing, States, and VA Deaths
color.cone | Depict colors geometrically
color.key | Add a thin key to the top of a plot
color.plot | Plot subgroups as colored points
color.plot.data.frame | Plot cases as colored points
color.plot.default | Plot subgroups as colored points
color.plot.formula | Plot cases as colored points
color.plot.loess | Contour plot of a regression surface
contour.plot | Display contours
data.image | Data Image
default.colors | Color schemes
dim.ordered | Is a dimension ordered?
GM.colors | Color schemes
gray.colors | Color schemes
hist.hclust | Histogram with hierarchical cluster breaks
Housing | Cars, Housing, States, and VA Deaths
labeled.curves | Plot labeled curves
linechart | Linechart
make.names | Make Syntactically Valid Names
make.unique | Make character strings unique
merge.factor | Merge factor levels
merge.hist | Merge histogram bins
merge.table | Table merging
merge.table.cells | Internal routines
merge.table.cost | Internal routines
mine.associations | Associations in a contingency table
OrRd.colors | Color schemes
parallel.plot | Parallel-coordinate plot
pca | Principal Component Analysis
plot.axes | Plot axes under projection
plot.breaks | Draw break locations
plot.hclust.trace | Plot a merging trace
plot.segments.ts | Plot time-series segments
predict.plot | Plot predictors versus response.
predict.plot.lm | Plot predictors versus residuals.
project | Project data into fewer dimensions
projection | Discriminative projection
RC.colors | Color schemes
read.array | Read and write arrays
RYB.colors | Color schemes
sort.levels | Sort levels of a factor
star.plot | Reordered and scaled star plot
States | Cars, Housing, States, and VA Deaths
text.plot | Make a plot of text labels
va.deaths | Cars, Housing, States, and VA Deaths
vrml.plot3d | View points in 3D
vrml.surface | View a surface in 3D
ward | Create a hierarchy by Ward's method
write.array | Read and write arrays
YlGnBu.colors | Color schemes
YR.colors | Color schemes


Choose aspect ratio

Description

Uses Cleveland's "banking to 45" rule to determine an optimal aspect ratio for a plot.

Usage

auto.aspect(x,y)

Arguments

x,y numeric vectors of coordinates defining a continuous curve, or multiple curves delimited by NAs. Alternatively, x can be a list of two vectors.

Value

An aspect ratio, suitable for the asp parameter to plot or plot.window.

Author(s)

Tom Minka

Examples

data(lynx)
plot(lynx)
plot(lynx,asp=auto.aspect(time(lynx),lynx))
[Package Contents]


Histogram with confidence intervals

Description

Same as hist except a confidence interval is drawn around each bin height.

Usage

bhist(x,b=NULL,z=1)

Arguments

x | a numerical vector
b | the number of bins, or a vector of break locations. If NULL, chosen automatically by hist.

Details

The width of the interval for height p is sqrt(p*(1-p)/n)*exp(-1/6/p/n).

Value

None.

Author(s)

Tom Minka

Examples

x <- c(rnorm(100,-2,0.5),rnorm(100,2,0.5))
b <- seq(-4,4,by=0.25)
bhist(x,b)


Boxplot with hierarchical cluster breaks

Description

A representation of a hierarchical clustering of predefined groups

Usage

boxplot.hclust(h,x,k=2:5,...)

Arguments

h | an hclust object
x | the list of vectors that was clustered to produce h (typically via ward)
k | a vector of the cluster cardinalities to plot
... | arguments passed to boxplot

Value

A boxplot of x is shown with blue lines cutting the x-axis. The tallest lines correspond to divisions made at the top of the hierarchy. By reading top to bottom, you can see how each cluster is subdivided. This can be far more illuminating than a plot of the hierarchy as a tree.

Author(s)

Tom Minka

See Also

hist.hclust, ward, break.ward


Equal-count breaks of a dataset

Description

Computes a set of breaks using the equal-count algorithm.

Usage

Author(s)

Tom Minka


Change-point analysis by clustering

Description

Divide a time-series into homogenous segments.

Usage

break.ts(x,n=2,trace=T,same.var=T)

Arguments

x | a numerical vector or ts object
n | the desired number of segments
trace | If TRUE, shows a merging trace via plot.hclust.trace
same.var | argument passed to ward

Details

Calls ward with sortx=F to cluster the series into segments. Only the marginal distribution of data is used; temporal smoothness, for example, is ignored.

Value

A vector of time breaks. The breaks are also plotted visually via plot.segments.ts.

Author(s)

Tom Minka

See Also

plot.segments.ts, plot.breaks

Examples

library(ts)
data(LakeHuron)
# single major change
break.ts(LakeHuron,2)
# merging trace suggests n=6 is also interesting:
break.ts(LakeHuron,6)
# interesting oscillation

data(treering)
break.ts(treering[1:500],9,same=T)
break.ts(treering[1:100],7,same=T)
# interesting multiscale structure

x <- c(rnorm(100),rnorm(300)*3,rnorm(200)*2)
b <- break.ts(x,3,same=F)
plot(x,type="l")
plot.breaks(b)


Quantize by clustering

Description

Quantize a one-dimensional variable by calling a clustering routine.

Usage

break.ward(x,n=2,plot=T)
break.hclust(x,n=2,method="ward",plot=T)
break.kmeans(x,n=2,plot=T)

Arguments

x | a numerical vector
n | the desired number of bins
method | argument given to hclust
plot | If TRUE, a histogram with break lines is plotted (hist.hclust or plot.breaks). For break.ward and break.hclust, also shows a merging trace (plot.hclust.trace).

Details

These are convenience routines which simply call the appropriate clustering routine (ward, hclust, or kmeans), convert the output to a break vector, and make plots.

Value

A break vector, suitable for use in cut or hist.

Author(s)

Tom Minka

Examples

x <- c(rnorm(700,-2,1.5),rnorm(300,3,0.5))
break.ward(x,2)
break.hclust(x,2,method="complete")
break.kmeans(x,2)

x <- c(rnorm(700,-2,0.5),rnorm(1000,2.5,1.5),rnorm(500,7,0.1))
break.ward(x,3)
break.hclust(x,3,method="complete")
break.kmeans(x,3)


Cars, Housing, States, and VA Deaths

Cars(mining) R Documentation

Cars Housing States and VA Deaths

Description

Cleaned-up versions of some popular R datasets.

Usage

data(Cars)
data(Housing)
data(States)
data(va.deaths)

Details

The variables are given more informative names, some irrelevant variables are dropped, erroneous values are fixed, and some variables are transformed (in the standardized case).

Value

The specified dataset is loaded as a data.frame. The first three also define a transformed dataset (ending in `T') where the variables are standardized.

Author(s)

Tom Minka

See Also

Cars93,Boston,state,VADeaths

Examples

data(States)
hist(States)
hist(StatesT)
w = pca(StatesT,2)
text.plot(project(StatesT,w),asp=1,cex=.6)
plot.axes(w)


Depict colors geometrically

Description

Plots named colors as points in a three-dimensional cone.

Usage

color.cone(col,cex=2,light=T,...)

Arguments

col | a vector of strings, naming colors.
cex | a number controlling the size of the points.
light | If TRUE, the cone will be surrounded by point light sources.

Details

The colors are mapped into Hue-Saturation-Lightness (HSL). Hue gives the angle around the cone, Saturation the radial distance from the center line, and Lightness the height from the base of the cone.

Value

Produces a VRML file which is opened by a VRML viewer.

Note

The high-lightness, high-saturation part of the cone will always be empty, because these colors are not achievable on computer displays (due to the RGB representation).

Author(s)

Tom Minka

References

Rich Franzen's Wheel of Saturation, Intensity, and Hue. http://home.att.net/~rocq/SIHwheel.html

Charles Poynton's Color FAQ. http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html

Examples

color.cone(YlGnBu.colors(8))
color.cone(YR.colors(16))
color.cone(RYB.colors(7))
color.cone(topo.colors(20))
# reveals how topo.colors is not sequential in lightness


Add a thin key to the top of a plot

Description

Similar to legend but takes up less space.

Usage

color.key(col=NULL,pch=NULL,labels=NULL,breaks=NULL,digits=2,cex=0.75)

Arguments

col | a vector of colors, one for each group. Assumed black if none given.
pch | a vector of symbols, one for each group. If less than two distinct symbols are given, no symbols are put in the key.
labels | a character vector giving the label of each group.
breaks | a numeric vector of boundaries between groups.
digits | number of digits to use for breaks.
cex | character expansion factor.

Value

A thin bar is placed at the top of the plot, just inside the plotting area. The bar is divided into equal-sized lengths, colored according to col. If pch is given, that symbol is plotted in the center of each segment. If labels is given, each label is placed at the center of the corresponding segment, just above the plotting area (using mtext). If breaks is given, the boundary between segments is also labeled with a number.

Author(s)

Tom Minka

See Also

color.plot

Examples

data(iris)
y = as.numeric(iris$Species)
plot(Sepal.Width ~ Sepal.Length, iris,col=y,pch=y)
color.key(1:3,1:3,levels(iris$Species))


Plot subgroups as colored points

Description

Like plot and text.plot but colors according to a third variable.

Usage

color.plot.default(x,y,z,labels=NULL,data=parent.frame(),
                   xlab,ylab,zlab,
                   xlim=NULL,ylim=NULL,
                   axes=T,key=T,add=F,nlevels=4,
                   color.palette=default.colors,col,
                   pch.palette=c(1,4,2,22,16,17,15),pch,
                   jitter=F,digits=2,mar,bg,...)

Arguments

x,y | numeric vectors of the same length.
z | a numeric vector or factor, same length as x and y.
labels | a character vector of labels, same length as z. If NULL, cases are plotted as points (default).
axes | If FALSE, no axes are plotted (but there may still be a key).
key | If FALSE, no key is plotted.
add | If FALSE, a new plot is made. If TRUE, points or labels are added to the existing plot.
nlevels | an integer. If z is numeric, it is color-coded using this many levels. (If z is a factor, color-coding follows the factor levels.)
color.palette | a vector of colors, arbitrary length, or a function with integer argument which generates a vector of colors (e.g. YlGnBu.colors). Used if col is not specified. If shorter than the number of levels, colors will be recycled and the plotting symbol will change.
col | a vector of colors, as in a call to plot. Used to explicitly set the color of each point.
pch.palette | a vector of plotting symbols, arbitrary length. If labels=NULL, the plot symbol will rotate through these when there aren't enough colors.
pch | a vector of plotting symbols, as in a call to plot. Used to explicitly set the symbol of each point.
digits | the number of digits to use in the color key when z is numeric.
bg | the background color
mar | figure margins (see par). If not specified, appropriate margins will be chosen automatically, which will not necessarily match the current value of par("mar").

Details

Each (x,y) point is plotted with a color determined by z. If z is a factor, each factor level is in a different color. If z is numeric, then it is color-coded by assigning each quantile a different color.

Despite the name, this function can also make plots using different symbols instead of colors. For example, if color.palette=1 then all points will be black but use different symbols.

When labels != NULL, the result is equivalent to text.plot with colors.

If key=TRUE and there is more than one color or symbol on the plot, a key is displayed at the top of the figure.

Value

A plot is produced.

Note

This function sets the figure margins permanently, so that you can draw on the color plot. Unfortunately, this also means future plots will use the same margins, until you change them with par("mar").

Author(s)

Tom Minka

See Also

color.plot.data.frame,color.plot.loess,clode{color.plot.glm},color.plot.knn,color.plot.tree,YlGnBu.colors

Examples

# See the examples for color.plot.data.frame


Plot cases as colored points

Description

Like plot and text.plot but colors according to the response variable.

Usage

color.plot.data.frame(data,labels=F,...)
color.plot.formula(formula, data=parent.frame(), ...)

Arguments

data | a data frame.
formula | a formula specifying a response and two predictors from data
labels | If NULL, cases are plotted as points. If T, cases are plotted as labels, according to rownames.
... | Extra arguments passed to color.plot.default.

Details

Calls color.plot.default with x as the first predictor in data, y as the second predictor, and z as the response. To get a different predictor/response breakdown than the default, use color.plot(formula, x, ...), which is shorthand for color.plot(model.frame(formula, x), ...).

Each case is plotted with a color determined by the response. If the response is a factor, each factor level is in a different color. If the response is numeric, then it is color-coded by assigning each quantile a different color.

Author(s)

Tom Minka

See Also

color.plot.default

Examples

data(iris)
color.plot(iris)
color.plot(Species ~ Petal.Length + Petal.Width, iris)
color.plot(Species ~ Petal.Length, iris)
color.plot(Species ~ Petal.Length, iris,jitter=T)
color.plot(iris, col=1)
color.plot(iris, col=c(1,2))

data(state)
x <- data.frame(state.x77)
color.plot(Murder ~ Frost + Illiteracy, x, labels=T, cex=0.5)


Contour plot of a regression surface

Usage

color.plot.loess(object,data,res=50,fill=F,add=fill,clip=T,...)

Arguments

object | a loess object.
data | data to use instead of model.frame(object).
res | resolution of the sampling grid in each direction.
fill | passed to contour.plot.
add | If TRUE, the contours are added to an existing plot. Otherwise a new plot is created.
clip | a polygon over which the surface is to be defined. Possible values are FALSE (no clipping), TRUE (clip to the convex hull of the data), or a matrix with two columns specifying (x,y) coordinates.
... | extra arguments to color.plot.data.frame

.

Details

The regression surface is evaluated at all points on a grid, clipped values are set to NA, and contour.plot is used to plot the contours.

If add=FALSE, the data is plotted on top using color.plot.data.frame.

Value

A plot is produced.

Author(s)

Tom Minka

See Also

contour.plot

Examples

data(Housing)
fit = loess(Price ~ Rooms + Low.Status, Housing)
color.plot(fit)


Color schemes

Description

Compute a color scheme with a specified number of levels.

Usage

default.colors(n)
default.colors.w(n)

YR.colors(n)
YlGnBu.colors(n)
OrRd.colors(n)
gray.colors(n)

RYB.colors(n)
BrBg.colors(n)
RC.colors(n)
GM.colors(n)

Arguments

n the number of colors desired

Details

The first two schemes are categorical, providing maximum separation in hue, intended for depicting unordered categories. default.colors has only dark colors, good for coloring points, while default.colors.w includes light colors, good for filling regions.

The next four schemes are sequential, from light to dark, with variation in hue to increase discrimination. They are intended for depicting ordered levels. The sequential order is more easily perceived with these schemes than with the built-in palettes heat.colors, terrain.colors, and topo.colors. The ordering can also be seen by the color-blind and when printed in black and white.

The main difference between the sequential schemes is the variation in hue, with YR.colors having the most variation and gray.colors having the least. Generally you should choose the amount of variation according to the number of levels. I recommend OrRd.colors for three levels, YlGnBu.colors for four to eight levels, and YR.colors beyond eight levels.

The last four schemes are double-ended or diverging schemes, which progress from one hue to a second hue, passing through white in the middle. They are intended for representing signed ordered levels, such as residuals. The main difference between them is the amount of separation between colors, so generally you use GM.colors when you want a few levels and RYB.colors when you want many.

These functions can be used as the color.palette parameter to filled.contour and color.plot, for example.

Value

A vector of strings, naming colors.

Author(s)

Tom Minka

References

The schemes in YlGnBu.colors, OrRd.colors, RYB.colors, and BrBg.colors are from ColorBrewer. The scheme in YR.colors is from Howard Seltman.

Mark A. Harrower and Cynthia A. Brewer. ColorBrewer: An Online Tool for Selecting Color Schemes for Maps, The Cartographic Journal, in press. http://www.colorbrewer.org/, http://www.personal.psu.edu/faculty/c/a/cab38/ColorBrewerBeta.html

Generalized color schemes for Mapping and Visualization. From Cynthia Brewer, Color Use Guidelines for Mapping and Visualization. Reprinted at the Gallery of Data Visualization by Michael Friendly. http://www.math.yorku.ca/SCS/Gallery/images/S12-fullstructureClean.gif

Dan Carr. Color perception, the importance of gray and residuals, on a choropleth map. Statistical Computing & Graphics Newsletter 5(1):16-20, 1994 http://cm.bell-labs.com/cm/ms/who/cocteau/newsletter/issues/back/v51.pdf

See Also

colors,rainbow,color.cone

Examples

data(Housing)
color.plot(Price ~ Rooms + Low.Status, Housing, bg=gray(0.5),
           color.palette=YlGnBu.colors)
color.plot(Price ~ Rooms + Low.Status, Housing, bg=gray(0.5),
           color.palette=YR.colors)
color.plot(Price ~ Rooms + Low.Status, Housing, bg=gray(0.5),
           color.palette=RYB.colors,nlevels=5)

# also see examples for color.cone


Display contours

Description

Create a filled or unfilled contour plot.

Usage

contour.plot(x,y,z,fill=F,
        levels=NULL,nlevels=if(is.null(levels)) 4 else length(levels),
                         level.data=z,
                         zlim,equal=F,pretty=T,lwd=2,drawlabels=F,
                         color.palette=YlGnBu.colors,bg=grey(0.5),
                         key=T,main="",...)

Arguments

x,y | locations at which the values in z are measured.
z | a matrix containing the values to be plotted (NAs are allowed).
fill | If TRUE, makes a filled contour plot.
levels | numeric vector of levels at which to draw contour lines. The next few arguments only apply to the case when levels==NULL.
nlevels | The number of contour lines to draw.
level.data | numeric vector to use for computing levels.
zlim | The range that the levels should cover. Defaults to the range of level.data.
equal | If TRUE, the levels are equally spaced over zlim. Otherwise they match the quantiles of level.data.
pretty | If TRUE, the levels are chosen to be round numbers.
lwd | width of the contour lines.
drawlabels | If TRUE, the contour lines are labeled with their level.
color.palette | a vector of colors, or a function which takes a number and returns a vector of that length.
bg | the background color.
key | If TRUE, a color key is drawn at the top of the plot. If key==2, the key of filled.contour is used.
main | the title of the plot.
... | extra arguments passed to contour or filled.contour.

Details

This is a wrapper function for contour and filled.contour whose main purpose is to provide a uniform interface and provide a decent automatic choice of levels.

If equal=FALSE, the levels are chosen according to the equal-count algorithm of break.quantile.

Author(s)

Tom Minka

See Also

contour,filled.contour, color.plot.loess

Examples

# see the examples for color.plot.loess


Data Image

Description

Each value in a data matrix is represented by a colored pixel.

Usage

data.image(x,reorder=T,scale=T,col=YR.colors(64),...)

Arguments

x | a matrix or data frame.
reorder | If TRUE, the rows and columns are reordered so that the data along each row and each column follows a linear trend. Can also be a vector of two logicals, indicating separately whether to reorder rows and/or columns.
scale | If TRUE, each column is scaled to have minimum 0 and maximum 1.
col | a vector of colors to use for representing values.
... | extra arguments to image.default.

Author(s)

Tom Minka

References

M. C. Minnotte and R. W. West. "The Data Image: A Tool For Exploring High Dimensional Data Sets." Proceedings of the ASA Section on Statistical Graphics, 1998. http://citeseer.nj.nec.com/72085.html http://math.usu.edu/~minnotte/research/pubs.html

See Also

YR.colors

Examples

data(USJudgeRatings)
data.image(USJudgeRatings,col=RC.colors(32))


Is a dimension ordered?

Description

Query whether each array dimension is ordered or not.

Usage

dim.ordered(x)

Arguments

x an array

Details

Intuitively, a dimension is ordered if its values are in a natural progression, such as (1,2,3) or ("one","two","three"). Programmatically, a dimension is considered ordered if and only if the corresponding dimnames vector has an ordered attribute set to T.

Value

A named logical vector, with an entry for each dimension, indicating whether it is ordered or not.

Author(s)

Tom Minka


Histogram with hierarchical cluster breaks

Description

A representation of a one-dimensional hierarchical clustering

Usage

hist.hclust(h,x,k=2:5)

Arguments

h | an hclust object
x | the numerical vector that was clustered to produce h
k | a vector of the cluster cardinalities to plot

Value

A histogram of x is shown with blue lines cutting the x-axis. The tallest lines correspond to divisions made at the top of the hierarchy. By reading top to bottom, you can see how each cluster is subdivided. This can be far more illuminating than a plot of the hierarchy as a tree.

Author(s)

Tom Minka

See Also

boxplot.hclust, ward, break.ward


Plot labeled curves

Description

Draws multiple curves, each with a properly-placed label and unique color/linestyle.

Usage

labeled.curves(x,y,se=NULL,labels,xlab,ylab,type="o",group,
               color.palette=default.colors(6),col,
               lty.palette=1:6,lty,lwd=2,jitter=0,
               legend=NULL,
               cex=par("cex"),horizontal=F,
               mar,bg=par("bg"),ylim,main="",...)

Arguments

x | a numeric vector giving the horizontal position of each point.
y | a matrix or data frame giving the vertical position of each point. Each column defines one curve.
se | a matrix or data frame, the same size as y, giving an error bound on each value.
labels | a character vector of labels for the lines. Defaults to the column names of y.
xlab,ylab | axis labels, by default the dimnames of y.
type | indicates whether to draw points, lines, or both. See plot.
group | a numeric vector specifying how to group cases when assigning colors.
color.palette | a vector of colors, arbitrary length, or a function with integer argument which generates a vector of colors. Used if col is not specified. If shorter than the number of curves, colors will be recycled and the line style will change.
col | a vector of colors, as in a call to plot. Used to explicitly set the color of each curve.
lty.palette | a vector of line styles, arbitrary length. The line style will rotate through these when there aren't enough colors.
lty | a vector of line styles, as in a call to plot. Used to explicitly set the style of each curve.
lwd | line width.
jitter | the amount by which to jitter the error bars, to avoid overplotting. jitter=0.02 is usually sufficient.
legend | If non-NULL, the labels are placed in a legend. Otherwise the labels are placed next to the lines.
cex | character expansion factor.
horizontal | If TRUE, the axes are laid out horizontally, so that the curves run vertically.
mar | a numerical vector giving the lines of margin on the four sides of the plot (see par). If missing, it is set according to auto.mar.
bg | background color.
ylim | desired plotting limits.
main | title for the plot.
... | extra arguments for low-level plotting commands.

Details

Point j in curve i is at (x[j],y[j,i]). Thus all curves must be the same length, and have points at the same horizontal positions. If y[i,j]=NA, then the curve has a break at the previous point, and resumes at the next non-NA point.

If se is given, then an error bar will be placed around each point.

Author(s)

Tom Minka

See Also

parallel.plot


Linechart

Description

Plot each data row as a curve.

Usage

linechart(y,se=NULL,effects=F,med=F,
          xscale=c("equal","linear","none"),...)

Arguments

y | a named vector or matrix.
se | a vector or matrix, same size as y, of error bounds. Alternatively, y can be list(y,se).
effects | If TRUE, the columns are shifted to have zero mean.
med | If TRUE and effects=TRUE, the columns are shifted to have zero median.
xscale | describes how the columns should be placed.
... | additional arguments to labeled.curves.

Details

If xscale="linear", the columns are placed to make each curve as straight as possible. If xscale="equal", the columns are placed similar to "linear" but with the constraint that they must be equally spaced. If xscale="none", the columns are placed in the order that they appear in the matrix. This is automatic if y has ordered columns (see dim.ordered). If se != NULL, error bars are drawn around each point.

Linecharts are a replacement for dotcharts and mosaics.

Author(s)

Tom Minka

See Also

dotchart, mosaicplot

Examples

# compare to a dotchart
data(VADeaths)
dotchart(VADeaths, main = "Death Rates in Virginia - 1940")
dimOrdered(VADeaths)[2] = F
linechart(VADeaths)
linechart(t(VADeaths))

# compare to a mosaicplot
data(HairEyeColor)
x <- margin.table(HairEyeColor,c(1,2))
dimOrdered(x) = F
mosaicplot(x)
x = t(x)
col = c("brown","blue","red","green")
linechart(row.probs(x),color.pal=col)
linechart(row.probs(x,se=T),color.pal=col)
linechart(row.probs(x,se=T),jitter=0.02,color.pal=col)
mosaicplot(x)
linechart(row.probs(t(x),se=T))

data(blood)
dimOrdered(blood) = F
linechart(row.probs(blood,se=T))

data(antacids)
dimOrdered(antacids) = F
linechart(row.probs(antacids,se=T))
mosaicplot(t(antacids))


Make Syntactically Valid Names

Description

Make syntactically valid names out of character vectors.

Usage

make.names(names, unique = FALSE)

Arguments

names | character (vector) to be coerced to syntactically valid names.
unique | logical; if TRUE, the resulting elements are unique. This may be desired for, e.g., column names.

Details

A syntactically valid name consists of letters, numbers, and the dot character and starts with a letter or the dot.

All invalid characters are translated to ".". A missing value is translated to "NA". Names which match R keywords have a dot appended to them.

If unique = TRUE then make.unique is used to append sequence numbers to duplicates (after coercion).

Value

A character vector of same length as names with each changed to a syntactically valid name.

See Also

names, character, data.frame.

Examples

make.names(c("a and b", "a_and_b"), unique=TRUE)
# "a.and.b"  "a.and.b1"

data(state)
state.name[make.names(state.name) != state.name]# those 10 with a space


Make character strings unique

Description

Makes the elements of a character vector unique by appending sequence numbers to duplicates.

Usage

make.unique(names,sep=".")

Arguments

names | a character vector
sep | a character string used to separate a duplicate name from its sequence number.

Details

The algorithm used by make.unique has the property that make.unique(c(A,B)) = make.unique(c(make.unique(A),B)).

In other words, you can append one string at a time to a vector, making it unique each time, and get the same result as applying make.unique to all of the strings at once.

If character vector A is already unique, then make.unique(c(A,B)) preserves A.

Value

a character vector of same length as names with duplicates changed.

Author(s)

Thomas P Minka

See Also

make.names

Examples

make.unique(c("a","a","a"))
make.unique(c(make.unique(c("a","a")),"a"))

make.unique(c("a","a","a.2","a"))
make.unique(c(make.unique(c("a","a")),"a.2","a"))

rbind(data.frame(x=1),data.frame(x=2),data.frame(x=3))
rbind(rbind(data.frame(x=1),data.frame(x=2)),data.frame(x=3))


Merge factor levels

Description

Merges factor levels with similar response distributions (assumed normal).

Usage

merge.factor(f,x,n,same.var=T,trace=T,xlab=NA,ylab=NA)

Arguments

f | a factor
x | a numerical vector, same length as f
n | the desired number of factor levels
same.var | argument passed to ward
trace | If TRUE, a merging trace is plotted (plot.hclust.trace)
xlab,ylab | axis labels. If NA, taken from f and x arguments.

Details

Calls ward(split(x,f)) to get a tree, cuts the tree, and constructs a new factor. The tree is shown via boxplot.hclust.

Value

A new factor, same length as f, but with n levels.

Author(s)

Tom Minka

Examples

n <- 20
x <- c(rnorm(n)+1, rnorm(n)+2, rnorm(n)*4+2)
f <- gl(3,n)
levels(f) <- c("a","b","c")
merge.factor(f,x,2,same.var=T)
merge.factor(f,x,2,same.var=F)

# an ordered factor
data(va.deaths)
merge.factor(va.deaths$Age,va.deaths$Rate,2)


Merge histogram bins

Description

Quantize a variable by merging similar histogram bins.

Usage

merge.hist(x,b=NULL,n=b)

Arguments

x | a numerical vector
b | the starting number of bins, or a vector of starting break locations. If NULL, chosen automatically by hist.
n | the desired number of bins.

Details

The desired number of bins is achieved by successively merging the two most similar histogram bins. The distance between bins of height (f1,f2) and width (w1,w2) is measured according to the chi-square statistic

w1*(f1-f)^2/f + w2*(f2-f)^2/f

where f is the height of the merged bin:

f = (f1*w1 + f2*w2)/(w1 + w2)

Value

A vector of bin breaks, suitable for use in hist, bhist, or cut. Two plots are shown: a bhist using the returned bin breaks, and a merging trace. The trace shows, for each merge, the chi-square distance of the bins which were merged. This is useful for determining the appropriate number of bins. An interesting number of bins is one that directly precedes a sudden jump in the chi-square distance.

Author(s)

Tom Minka

Examples

x <- c(rnorm(100,-2,0.5),rnorm(100,2,0.5))
b <- seq(-4,4,by=0.25)
merge.hist(x,b,10)
# according to the merging trace, n=5 and n=11 are most interesting.

x <- runif(1000)
b <- seq(0,1,by=0.05)
merge.hist(x,b,10)
# according to the merging trace, n=6 and n=9 are most interesting.
# because the data is uniform, there should only be one bin,
# but chance deviations in density prevent this.
# a multiple comparisons correction in merge.hist may fix this.


Table merging

Description

Merges similar rows and columns of a contingency table.

Usage

merge.table(x, bins=rep(2,length(ds)), ds=1:length(dim(x)))

Arguments

x | a table
bins | the desired number of levels for each dimension being merged. a numeric vector, the same length as ds.
ds | a vector of dimensions to merge, either by name or number. default is all of them.

Details

The desired table dimensions are achieved by successively merging the two most similar slices. (`Slice' generalizes `row' and `column' to higher-dimensional tables.) The distance between slices is measured according to the chi-square statistic. Merging two slices means adding together their counts, and concatenating their labels with a comma in between. If a dimension is ordered (according to dim.ordered), only adjacent slices are considered for merging, and their labels are concatenated with a dash in between.

Value

A merged table. The total count is the same as x. A merging trace is plotted which shows, for each merge, the chi-square distance of the slices which were merged. This is useful for determining the appropriate dimensions. An interesting number is one that directly precedes a sudden jump in the chi-square distance.

Author(s)

Tom Minka

See Also

sort.table, mosaicplot, linechart

Examples

i <- factor(c(1,1,2,2,3,3,4,4))
j <- factor(c(3,4,3,4,1,2,1,2))
x <- table(i,j)
merge.table(x,c(2,2))

i <- factor(c(1,1,3,3,2,2,4,4))
j <- factor(c(2,4,2,4,1,3,1,3))
x <- table(i,j)
merge.table(x,c(2,2))

# one ordered dimension
data(education)
merge.table(education,c(3,2))

data(occupation)
merge.table(occupation,c(3,4))


Internal routines

Description

Internal routines for merge.table

Usage

merge.table.cost(x,v,cost)
merge.table.cost.inorder(x,v,cost)
merge.table.cells(x,v,i,j)

Author(s)

Tom Minka


Associations in a contingency table

Description

Find unusually frequent variable combinations.

Usage

mine.associations(x,top=10,targets=NULL)

Arguments

x | a contingency table
top | the number of top associations to return
targets | a character vector of table variables, one of which must be included in every returned association.

Details

Enumerates all two-way marginal tables, sorts the cells by lift, and returns the top. The formula for lift is

frac{p(i,j)}{p(i)p(j)}

.

Value

A data frame where the first column is Lift and the remaining columns correspond to the variables of x. Each row describes a cell of x, where marginalized variables have value NA. The lift value describes the ratio of the actual count in the cell versus the expected count under independence.

Author(s)

Tom Minka

Examples

data(Titanic)
mine.associations(Titanic)
# Females are twice as likely to survive as the average person.
# Members of 3rd class are twice as likely to be children as the average person.
# Etc.

# focus on associations with survival
mine.associations(Titanic,target="Survived")

# focus on children
mine.associations(Titanic[,,1,],target="Survived")


Parallel-coordinate plot

Description

Plots a data matrix using parallel coordinates.

Usage

parallel.plot(x,yscale=c("linear","range","none"),
              xscale=c("equal","linear","none"),proto=T,...)

Arguments

x | a data matrix or frame. Only numeric columns will be plotted.
yscale | describes how the columns should be scaled.
xscale | describes how the columns should be placed.
proto | If TRUE and the response variable is a factor, then only the mean value for each response is plotted. See prototypes.
... | Extra arguments to labeled.curves.

Details

Let the rows of the matrix be cases and the columns be dimensions. Each dimension is laid out as a vertical axis, and the value for each case is plotted as a point on that axis. Points corresponding to the same case are connected by lines. Thus each case is represented by a curve or profile, moving horizontally from dimension to dimension.

To enhance readability, the dimensions should usually be shifted to have a common center and scaled to have comparable units. This is controlled by yscale. If yscale="linear", the dimensions are automatically shifted and scaled by the linear profiles method. That is, the profiles are made to be as straight as possible. This may result in negative scaling for a dimension, i.e. the axis is reversed so that moving up means a lower value. When this happens, the dimension name is prepended with a minus sign. If yscale="range", the dimensions are shifted and scaled (by a positive number) so that the data ranges from 0 to 1 on each axis. If yscale="none", the dimensions are plotted as-is.

Another important choice is the ordering and spacing of the axes on the plot. If xscale="linear", the axes are placed according to the linear profiles method. If xscale="equal", the axes are placed similarly to "linear" but with the constraint that they must be equally spaced. If xscale="none", the axes are placed in the order that they appear in the matrix.

If the data frame has a categorical response, the profiles are colored according to the response. The color scheme can be adjusted using the arguments to labeled.curves.

Author(s)

Tom Minka

See Also

parallel.cases,star.plot

Examples

data(iris)
parallel.plot(iris)
parallel.plot(iris,proto=F,labels=NULL)


Principal Component Analysis

Description

Computes a projection matrix that preserves spread.

Usage

pca(x,k=1)

Arguments

x | a data frame.
k | the number of dimensions to project down to.

Details

The projection is chosen so that the projected data is as "spread out" as possible, measured according to the determinant of the covariance matrix. This turns out to be the top k eigenvectors of the data covariance matrix.

The projection is "stabilized" so that small changes in the data do not cause sign flips in the projection.

Value

A matrix with named rows matching the numeric columns of x and columns named h1, ..., hk. Each column denotes a new dimension to be obtained as a linear combination of the numeric variables in x.

Author(s)

Tom Minka

See Also

project, projection, pca in the multiv package

Examples

data(Housing)
w = pca(HousingT,k=2)
plot(project(HousingT,w),asp=1)
plot.axes(w)


Plot axes under projection

Description

Shows how unit vectors along the original dimensions appear under a projection.

Usage

plot.axes(w,col=2,origin,keep=0.2)

Arguments

w | a numeric array with two columns and named rows
col | color of arrows
origin | If T, arrows emerge from (0,0). If F, arrows emerge from the center of the figure. If not given, arrows emerge from (0,0) if (0,0) is visible, otherwise from the figure center.
keep | a length in inches, below which an arrow is not plotted.

Details

Each row of the array specifies a location in the figure. This location can be understood as the place where a unit vector along one of the original dimensions would appear. An arrow is drawn from the origin pointing toward this location and labeled with the row name. The relative length of the arrow is determined by the distance of the location from the origin, but all arrows are scaled as much as possible, to reduce crowding, while remaining inside the figure limits. Arrows which are very short are not plotted at all.

Value

Uses arrows to draw arrows on top of the current plot.

Author(s)

Tom Minka

See Also

project, pca, projection


Draw break locations

Description

Draws lines to indicate break locations.

Usage

plot.breaks(b)

Arguments

b a numeric vector

Value

Uses segments to draw thick blue vertical lines on top of the current plot, at the given locations.

Author(s)

Tom Minka

See Also

plot.hclust.breaks, plot.segments.ts, break.kmeans


Plot a merging trace

Description

Plots the cost of successive merges in a hierarchical clustering

Usage

plot.hclust.trace(h,k=1:10)

Arguments

h | an hclust object
k | a vector of the cluster cardinalities to plot

Value

The trace shows, for each merge, the distance of the clusters which were merged. This is useful for determining the appropriate number of clusters. An interesting number of clusters is one that directly precedes a sudden jump in distance.

Author(s)

Tom Minka

See Also

ward, break.ward


Plot time-series segments

Description

Shows how the mean level of a time-series varies between segments.

Usage

plot.segments.ts(x,b)

Arguments

x | a numeric vector or ts object
b | a numeric vector of break times

Value

Plots the time series as a line, then draws a blue horizontal line through each segment, at the mean value of the segment.

Author(s)

Tom Minka

See Also

break.ts, plot.breaks


Plot predictors versus response.

Description

Makes a matrix of pairwise scatterplots with lowess-type trend lines.

Usage

predict.plot(...)
predict.plot.formula(formula,data=parent.frame(),...)
predict.plot.data.frame(x,layout=NULL,partial=NULL,
                           rtype=c("prob","logit","probit"),
                           highlight,se=T,
                           identify.pred=F,
                           mcol=0,mlwd=2,
                           scol="red",slwd=2,
                           span=2/3,degree=2,family="symmetric",
                           mar=NA,bg=par("bg"),
                           xaxt=par("xaxt"),yaxt=par("yaxt"),
                           col=1,asp=NULL,
                           given=NULL,given.lab=NULL,nlevels=2,
                           pretty=T,key=!is.null(given),
                           color.palette=default.colors,
                           pch.palette=default.pch,
                           main=NULL,xlab,ylab,...)

Arguments

formula | a formula specifying the response and predictor variables
data,x | a data frame with at least two columns
partial | a model from which to compute partial residuals (used by predict.plot.lm).
mcol,mlwd | If plotting partial residuals of an lm, the color and width of the model predictions.
layout | a vector c(rows,cols) specifying the desired layout of panels. Otherwise chosen automatically based on the size of the plotting window.
highlight | a logical vector specifying which predictors to highlight.
se | If TRUE, show standard errors in linecharts.
scol,slwd | color and width of trend lines.
span,degree,family | parameters for the trend line (see loess).
rtype | how a factor response should be handled when drawing a trend line.
identify.pred | A character vector of predictor names for which to interactively identify points. If TRUE, done for all predictors.
mar | margins within each panel
xaxt,yaxt | arguments to par
col | plotting color for symbols
asp | Aspect ratio for each panel. If "auto", the aspect ratio is chosen automatically based on the trend line and auto.aspect.
given,given.lab,nlevels,pretty,key,bg,color.palette,pch.palette | used for conditioning plots.
main,xlab,ylab | axis labels.
... | extra arguments passed to predict.plot.data.frame or plot.

Value

If the predictor is numeric, makes a scatterplot with loess line on top. If the predictor is a factor, makes a linechart.

Author(s)

Tom Minka

See Also

loess,model.plot

Examples

data(Cars)
predict.plot(Price~.,CarsT)
fit = lm(Price~.,CarsT)
predict.plot(Price~.,CarsT,partial=fit)
# same thing using predict.plot.lm
predict.plot(fit,partial=T)


Plot predictors versus residuals.

Description

Makes a matrix of pairwise scatterplots with lowess-type trend lines.

Usage

predict.plot.lm(object,data,partial=F,ylab,...)

Arguments

object | the output of lm.
data | a data frame to use instead of model.frame(object).
partial | If TRUE, plot partial residuals instead of residuals.
ylab | axis label.
... | extra arguments for predict.plot.data.frame.

Details

Partial residuals are computed by fitting a new model with the predictor removed, which is different from residuals(type="partial").

Value

A plot similar to predict.plot, but where the vertical axis is residuals. These plots can be used to judge which predictors should be added to the model.

Author(s)

Tom Minka

See Also

predict.plot

Examples

# see the examples for predict.plot


Project data into fewer dimensions

Description

Reduces the dimensionality of a data set.

Usage

project(x,w)

Arguments

x | a data frame
w | a matrix with named rows and columns

Details

Each column of w specifies a new variable, which is to be constructed by combining existing variables according to the given weights.

Value

A data frame where the variables named in the rows of w are replaced by new variables named in the columns of w. Other variables are left unchanged.

Author(s)

Tom Minka

See Also

pca, projection, plot.axes

Examples

data(iris)
w = projection(iris,k=2)
# w only involves the continuous attributes
# the new variables are h1 and h2
x = project(iris,w)
color.plot(x)
plot.axes(w)


Discriminative projection

Description

Finds a projection matrix that separates data groups.

Usage

projection(x,y,k=1,given=NULL,type=c("mv","m","v"),...)

Arguments

x | a data frame of variables to project.
y | a factor or numeric vector which defines the groups to separate. If y is not given, it is taken to be the response variable of x (the last column if x is not a model.frame).
k | the number of dimensions to project x down to.
given | A matrix specifying axes to avoid. The projection matrix will be orthogonal to given.
type | see below.
... | additional parameters depending on type.

Details

This function only uses the second-order statistics of the data (means and covariances of the groups).

If type="m", the within-group covariances are assumed equal and the projection will try to separate the projected means.

If type="v", the within-group means are assumed equal and the projection will try to separate the projected covariances.

If type="mv", the projection will try to separate the projected means and covariances, by maximizing the divergence between the projected classes (as Gaussians).

If y is a numeric vector, overlapping classes are defined by grouping data points with similar values of y. The optional argument span controls how big the classes will be (as a percentage of the dataset), and res controls the amount of overlap. The total number of classes will be res/span. The default values are usually acceptable.

The projection is "stabilized" so that small changes in the data do not cause sign flips in the projection.

Value

A matrix suitable for input to project, with named rows matching columns of x and columns named h1, ..., hk. Each column denotes a new dimension to be obtained as a linear combination of the variables in x.

Author(s)

Tom Minka

References

m-projection is Fisher's linear discriminant analysis. mv-projection is heteroscedastic discriminant analysis:

N. Kumar and A.G. Andreou. Heteroscedastic discriminant analysis and reduced rank HMMs for improved speech recognition. Speech Communication 26: 283-297, 1998.

The case when y is numeric is sliced inverse regression:

K.-C. Li. Sliced inverse regression for dimension reduction. Journal of the American Statistical Association 86(414): 316-327, 1991.

See Also

project,pca

Examples

# illustrate difference between (m,v,mv)
library(MASS)
m1 <- c(6,6)
v1 <- array(c(2,1.9,1.9,2),c(2,2))
#v1 <- array(c(1,0,0,1),c(2,2))
x1 <- mvrnorm(100,m1,v1)
m2 <- c(0,0)
v2 <- array(c(20,0,0,10),c(2,2))
x2 <- mvrnorm(300,m2,v2)
x = as.data.frame(rbind(x1,x2))
y = factor(c(rep(1,nrow(x1)),rep(2,nrow(x2))))
plot(x[,1],x[,2],col=1,xlab="",ylab="",asp=1)
points(x2[,1],x2[,2],col=2)
w = projection(x,y,type="m")
abline(0,w[2]/w[1],col=3)
w = projection(x,y,type="v")
abline(0,w[2]/w[1],col=4)
w = projection(x,y,type="mv")
abline(0,w[2]/w[1],col=5)
my.legend(1,c("m","v","mv"),col=3:5,lty=1)

# regression projection
x1 <- 2*runif(200)-1
x2 <- 2*runif(200)-1
y <- x1^2/2 + x2^2
x <- data.frame(x1,x2)
color.plot(x[,1],x[,2],y)
w = projection(x,y)
abline(0,w[2]/w[1],col=4)


Read and write arrays

Description

Read data into an array from the console or file

Usage

read.array(file, sep = "", quote = "\"", skip = 0)

Details

The array can have one of several formats. The preferred format, produced by write.array, looks like cvar.nam rvar.1.nam ... rvar.k.nam cvar.lev.1 ... cvar.lev.l rvar.1.lev.1 ... rvar.k.lev.1 ... ... ...

Value

An array.

Author(s)

Tom Minka

Examples

#read.array("class/data/ex9-21.dat")
#x <- read.array("class/data/mm2-14.dat")
#x <- read.array("class/data/arizona.txt")


Sort an array

Description

Sort the cells of an array

Usage

sort.cells(x)

Arguments

x an array

Details

Converts x to a data frame and calls sort.data.frame.

Value

A data frame representation of x, sorted by cell value.

Author(s)

Tom Minka

See Also

sort.data.frame

Examples

data(Titanic)
sort.cells(Titanic)

data(HairEyeColor)
sort.cells(HairEyeColor)


Sort rows of a data frame

Description

Re-orders data frame rows so that a column is sorted.

Usage

sort.data.frame(df,f=ncol(df))

Arguments

df | a data frame
f | the name or number of a column of df, or a numeric vector to play the role of a column of df.

Value

A reordered version of df where the values in column f are in ascending order.

Author(s)

Tom Minka

See Also

sort.cells

Examples

data(mtcars)
sort.data.frame(mtcars,"mpg")


Sort levels of a factor

Description

The levels of a factor are sorted according to a summary statistic.

Usage

sort.levels(f,x,fun=median)

Arguments

f | a factor
x | a vector, same length as f
fun | function to use to summarize groups of x

Value

A copy of f with re-ordered levels.

Author(s)

Tom Minka

Examples

data(OrchardSprays)
sort.levels(OrchardSprays$treatment, OrchardSprays$decrease)
sort.levels(OrchardSprays$treatment, OrchardSprays$decrease, fun=mean)


Sort rows and columns of a contingency table

Description

Score rows and columns via correspondence analysis, then sort the scores.

Usage

sort.table(x)

Arguments

x a contingency table

See Also

mosaicplot

Examples

data(blood)
sort.table(blood)


Reordered and scaled star plot

Description

Automatically reorders and scales the variables to make a readable star plot.

Usage

star.plot(x,proto=T,reorder=T,scale=T,...)

Arguments

x | a matrix or data frame. Each row makes one star.
proto | If TRUE and the response variable is a factor, then only the mean value for each response is plotted. See prototypes.
reorder | If TRUE, the rows and columns are reordered so that the data along each row and each column follows a linear trend. Can also be a vector of two logicals, indicating separately whether to reorder rows and/or columns.
scale | If TRUE, each column is scaled to have minimum 0 and maximum 1.
... | additional arguments for stars.

Author(s)

Tom Minka

See Also

stars

Examples

data(iris)
star.plot(iris)


U.S. state area 1990

Usage

data(state.area)

Details

state.area is a named vector of the 1990 U.S. state land areas, including the District of Columbia, in square miles. The numbers are more accurate and up-to-date than the ones in data(state).

References

The data was obtained from http://www.census.gov/population/censusdata/90den_stco.txt and edited into R format. County areas can also be obtained from the above link.

See Also

state.pop, state


U.S. state population 1790-1990

Usage

data(state.pop)

Details

state.pop is a matrix containing the population of each U.S. state, including the District of Columbia, from 1790 to 1990 in ten-year increments. The rows are the years "1790" to "1990" and the columns are state names.

References

The data was obtained from http://merrill.olm.net/pdocs/feas/pop/pop1790_1990/pii.txt and edited into R format.

See Also

state.area, state.name, state

Examples

dotchart(sort(log(state.pop["1990",])))

# distribution of growth rates over time
rates <- diff(log(state.pop))
boxplot(as.data.frame(t(rates)))


Make a plot of text labels

Description

Like text except it creates a new plot with limits chosen to make all labels visible.

Usage

text.plot.default(x,y,labels,xlab,ylab,xlim=NULL,ylim=NULL,
                  cex=par("cex"),adj=NULL,srt=0,axes=T,...)
text.plot.data.frame(data,labels=rownames(data),...)
text.plot.formula(formula,data=parent.frame(),...)

Arguments

x,y | numeric vectors, same length
data | a data frame with at least two columns
formula | a formula specifying a response and predictor variable
labels | character vector, same length as x
srt | rotation angle as in text.
adj | text justification as in text.

Details

The main job of text.plot is finding the right plot limits so that all labels are visible. It does this by computing the bounding box of each label (taking into account text rotation and justification) and solving a system of inequalities which ensure that each label fits entirely into the plot window.

Author(s)

Tom Minka

Examples

data(state)
x <- data.frame(state.x77)
text.plot(x$Frost, x$HS.Grad, rownames(x))
# same thing, using text.plot.formula
text.plot(HS.Grad ~ Frost, x)
# notice how the limits change
text.plot(HS.Grad ~ Frost, x, srt=45)
text.plot(HS.Grad ~ Frost, x, srt=90)


View points in 3D

Description

Creates a VRML scene with the given points.

Usage

vrml.plot3d.default(x,y,z,data=parent.frame(),xlab,ylab,zlab,
                    pch=0,col=3,scale=c(1,1,1),file.name=NULL,
                    cex=1,cex.axis=12,light=T,axes=T,...)
vrml.plot3d.data.frame(frame,...)
vrml.plot3d.formula(formula,data,...)

Arguments

x,y,z | numeric vectors giving the coordinates of the points.
frame | a data frame with three columns.
data | an environment in which to lookup x,y,z.
xlab,ylab,zlab | axis labels.
pch | a numeric code for the graphic object to place at each location. See details.
col | a single color or vector of colors, used to color the points.
scale | a vector of 3 numbers, defining the size of the box into which the points are placed. You can control the aspect ratio this way.
file.name | a filename (with or without the .wrl extension) to receive the VRML. If NULL, a temporary name is chosen.
cex | a scale factor for the objects.
cex.axis | a scale factor for the axis labels.
light | If TRUE, the scene will contain a light at each corner of the cube, with no headlight. Otherwise, the scene will contain no lights and rely on the headlight only.
axes | If TRUE, a box with axis labels is drawn around the points.
... | additional arguments to pass to the internal drawing routines, or to pass through to vrml.plot3d.default (for the data.frame and formula methods).

Details

A VRML scene description file is created, and opened with a browser if one is available.

VRML is a standard language for describing 3D scenes, and the file produced by this function should be portable across all machines with a VRML browser.

If pch=0, a cube is placed at each location.
If pch=1, a sphere is placed at each location.
If pch=".", a dot is placed at each location.
The latter option is the fastest, and will be chosen automatically if
the scale is small or the dataset is large.

Author(s)

Tom Minka

References

http://web3d.vapourtech.com/tutorials/vrml97/

www.wed3d.org/resources/vrml_ref_manual/Book.html

Examples

data(Housing)
w = pca(HousingT,k=3)
x = project(HousingT,w)
plot.new()
vrml.plot3d(x)


View a surface in 3D

Description

Creates a VRML scene with a shaded surface.

Usage

vrml.surface.default(x,y,z,xlab=NULL,ylab=NULL,zlab=NULL,
                     col="gray",scale=c(1,1,1),file.name=NULL,
                     cex.axis=12,light=F,...)

Arguments

x,y | locations of grid lines at which the values in z are measured.
z | a matrix containing the values to be plotted (NAs are allowed).
xlab,ylab,zlab | axis labels. If NULL, taken from the deparsed expressions for x,y,z.
col | the color of the surface.
scale | a vector of 3 numbers, defining the size of the box into which the surface is placed. You can control the aspect ratio this way.
file.name | a filename (with or without the .wrl extension) to receive the VRML. If NULL, a temporary name is chosen.
cex.axis | a scale factor for the axis labels.
light | If TRUE, the scene will contain its own light and no headlight. Otherwise, the scene will contain no lights and rely on the headlight only.
border | If TRUE, a grid will be drawn on top of the surface.
creaseAngle | a parameter controlling the smoothness of the surface. When it is small, faces at large angles to each other will create visible "creases".
... | additional arguments for internal drawing routines.

Details

A VRML scene description file is created, and opened with a browser if one is available.

VRML is a standard language for describing 3D scenes, and the file produced by this function should be portable across all machines with a VRML browser.

This function is similar to persp except it creates a 3D scene which can be manipulated with a VRML viewer.

Author(s)

Tom Minka

See Also

persp,vrml.plot3d

Examples

#  The Obligatory Mathematical surface.
#  Rotated sinc function.
x <- seq(-10, 10, length= 30)
y <- x
f <- function(x,y) { r <- sqrt(x^2+y^2); 10 * sin(r)/r }
z <- outer(x, y, f)
z[is.na(z)] <- 1
vrml.surface(x,y,z)
vrml.surface(x,y,z,border=T)


Create a hierarchy by Ward's method

Description

Produces a hierarchical clustering of one-dimensional data via Ward's method.

Usage

ward(x, n=rep(1,length(x)), s=rep(1,length(x)), sortx=T, same.var=T)

Arguments

x | a numerical vector, or a list of vectors.
n | if x is a vector of cluster means, n is the size of each cluster.
s | if x is a vector of cluster means, s is the sum of squares in each cluster. only needed if same.var=F.
sortx | if sortx=F, only clusters which are adjacent in x can be merged. Used by break.ts.

Details

Repeatedly merges clusters in order to minimize the clustering cost. By default, it is the same as hclust(method="ward"). If same.var=T, the cost is the sum of squares:

sum_c sum_{i in c} (x_i - m_c)^2

The incremental cost of merging clusters ca and cb is

(n_a*n_b)/(n_a+n_b)*(m_a - m_b)^2

It prefers to merge clusters which are small and have similar means.

If same.var=F, the cost is the sum of log-variances:

sum_c n_c*log(1/n_c*sum_{i in c} (x_i - m_c)^2)

It prefers to merge clusters which are small, have similar means, and have similar variances.

If x is a list of vectors, each vector is assumed to be a cluster. n and s are computed for each cluster and x is replaced by the cluster means. Thus you can say ward(split(x,f)) to cluster the data for different factors.

Value

The same type of object returned by hclust.

Bugs

Because of the adjacency constraint used in implementation, the clustering that results from sortx=T and same.var=F may occasionally be suboptimal.

Author(s)

Tom Minka

See Also

hclust, plot.hclust.trace, hist.hclust, boxplot.hclust, break.ward, break.ts, merge.factor

Examples

x <- c(rnorm(700,-2,1.5),rnorm(300,3,0.5))
hc <- ward(x)
opar <- par(mfrow=c(2,1))
plot.hclust.trace(hc)
hist.hclust(hc,x)
par(opar)

x <- c(rnorm(700,-2,0.5),rnorm(1000,2.5,1.5),rnorm(500,7,0.1))
hc <- ward(x)
opar <- par(mfrow=c(2,1))
plot.hclust.trace(hc)
hist.hclust(hc,x)
par(opar)

data(OrchardSprays)
x <- OrchardSprays$decrease
f <- factor(OrchardSprays$treatment)
# shuffle levels
#lev <- levels(OrchardSprays$treatment)
#f <- factor(OrchardSprays$treatment,levels=sample(lev))
hc <- ward(split(x,f))
# is equivalent to:
#n <- tapply(x,f,length)
#m <- tapply(x,f,mean)
#s <- tapply(x,f,var)*n
#hc <- ward(m,n,s)
boxplot.hclust(hc,split(x,f))