Rev 34057 | Rev 34720 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
\name{Extract}\title{Extract or Replace Parts of an Object}\alias{Extract}\alias{Subscript}\alias{[}\alias{[[}\alias{$}\alias{[<-}\alias{[[<-}\alias{$<-}\concept{delete}\description{Operators acting on vectors, arrays and lists to extract orreplace subsets.}\usage{x[i]x[i, j, \dots , drop = TRUE]x[[i]]x[[i, j, \dots]]x$name}\arguments{\item{x}{object from which to extract elements or in which to replace elements.}\item{i, j, \dots, name}{indices specifying elements to extract or replace. \code{i, j} are\code{numeric} or \code{character} or empty whereas \code{name} must becharacter or an (unquoted) name. Numeric values are coerced tointeger as by \code{\link{as.integer}}. For \code{[[} and \code{$}character strings are normally partially matched to the names of theobject if exact matching does not succeed.For \code{[}-indexing only: \code{i, j, \dots} can belogical vectors, indicating elements/slices to select. Such vectorsare recycled if necessary to match the corresponding extent. Whenindexing arrays, \code{i} can be a (single) matrix with as manycolumns as there are dimensions of \code{x}; the result is then avector with elements corresponding to the sets of indices in eachrow of \code{i}.\code{i, j, \dots} can also be negative integers, indicatingelements/slices to leave out of the selection.}\item{drop}{For matrices, and arrays. If \code{TRUE} theresult is coerced to the lowest possible dimension (see examplesbelow). This only works for extracting elements, not for thereplacement forms.}}\details{These operators are generic. You can write methods to handle subsettingof specific classes of objects, see \link{InternalMethods} as well as\code{\link{[.data.frame}} and \code{\link{[.factor}}. Thedescriptions here apply only to the default methods.The most important distinction between \code{[}, \code{[[} and\code{$} is that the \code{[} can select more than one element whereasthe other two select a single element. \code{$} does not allowcomputed indices, whereas \code{[[} does. \code{x$name} is equivalentto \code{x[["name"]]} if \code{x} is recursive(see \code{\link{is.recursive}}) and \code{NULL} otherwise.The \code{[[} operator requires all relevant subscripts to be supplied.With the \code{[} operator an empty index (a comma separated blank)indicates that all entries in that dimension are selected.If one of these expressions appears on the left side of an assignmentthen that part of \code{x} is set to the value of the right hand sideof the assignment.Indexing by factors is allowed and is equivalent to indexing by thenumeric codes (see \code{\link{factor}}) and not by the charactervalues which are printed (for which use \code{[as.character(i)]}).When operating on a list, the \code{[[} operator gives the specifiedelement of the list while the \code{[} operator returns a list withthe specified element(s) in it.As from \R 1.7.0 \code{[[} can be applied recursively to lists, sothat if the single index \code{i} is a vector of length \code{p},\code{alist[[i]]} is equivalent to \code{alist[[i1]]\dots[[ip]]}providing all but the final indexing results in a list.The operators \code{$} and \code{$<-} do not evaluate their secondargument. It is translated to a string and that string is used tolocate the correct component of the first argument.When \code{$<-} is applied to a \code{NULL} \code{x}, it coerces\code{x} to \code{list()}. This is what happens with \code{[[<-} is\code{y} is of length greater than one: if \code{y} has length 1 or 0,\code{x} is coerced to a zero-length vector of the type of \code{value},As from \R 1.9.0 both \code{$} and \code{[[} can be applied toenvironments. Only character arguments are allowed and no partialmatching is done (this is in contrast to the behavior for lists). Thesemantics of these operations is basically that of \code{get(i, env=x,inherits=FALSE)}. If no match is found then \code{NULL} isreturned. The assignment versions, \code{$<-} and\code{[[<-}, can also be used. Again, only character arguments areallowed and no partial matching is done. The semantics in this caseare those of \code{assign(i, value, env=x, inherits=FALSE)}. Such anassignment will either create a new binding or change the existingbinding in \code{x}.Negative indices are not allowed in index matrices. \code{NA} and zerovalues are allowed: rows of an index matrix containing a zero areignored, whereas rows containing an \code{NA} produce an \code{NA} inthe result.}\section{NAs in indexing}{When subscripting, a numerical, logical or character \code{NA} picksan unknown element and so returns \code{NA} in the correspondingelement of a logical, integer, numeric, complex or character result,and \code{NULL} for a list.When replacing (that is using subscripting on the lhs of anassignment) \code{NA} does not select any element to be replaced. Asthere is ambiguity as to whether an element of the rhs shouldbe used or not (and \R handled this inconsistently prior to \R 2.0.0),this is only allowed if the rhs value is of length one (so the twointerpretations would have the same outcome).}\section{Argument matching}{Note that these operations do not match their index arguments in thestandard way: argument names are ignored and positional matching only isused. So \code{m[j=2,i=1]} is equivalent to \code{m[2,1]} and\strong{not} \code{m[1,2]}.This may not be true for methods defined for them; for example it isnot for the \code{data.frame} methods described in\code{\link{[.data.frame}}.To avoid confusion, do not name index arguments(but \code{drop} must be named).}\references{Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)\emph{The New S Language}.Wadsworth \& Brooks/Cole.}\seealso{\code{\link{list}}, \code{\link{array}}, \code{\link{matrix}}.\code{\link{[.data.frame}} and \code{\link{[.factor}} for thebehaviour when applied to data.frame and factors.\code{\link{Syntax}} for operator precedence, and the\emph{R Language} reference manual about indexing details.%% Fixme: Link (to html in 'help.start()', pdf from 'ref manual',%% 'info' from ESS, see \url{http://cran.R-project.org/manuals.html}.}\examples{x <- 1:12; m <- matrix(1:6,nr=2); li <- list(pi=pi, e = exp(1))x[10] # the tenth element of xx <- x[-1] # delete the 1st element of xm[1,] # the first row of matrix mm[1, , drop = FALSE] # is a 1-row matrixm[,c(TRUE,FALSE,TRUE)]# logical indexingm[cbind(c(1,2,1),3:1)]# matrix indexm <- m[,-1] # delete the first column of mli[[1]] # the first element of list liy <- list(1,2,a=4,5)y[c(3,4)] # a list containing elements 3 and 4 of yy$a # the element of y named a## non-integer indices are truncated:(i <- 3.999999999) # "4" is printed(1:5)[i] # 3## recursive indexing into listsz <- list( a=list( b=9, c='hello'), d=1:5)unlist(z)z[[c(1, 2)]]z[[c(1, 2, 1)]] # both "hello"z[[c("a", "b")]] <- "new"unlist(z)## check $ and [[ for environmentse1 <- new.env()e1$a <- 10e1[["a"]]e1[["b"]] <- 20e1$bls(e1)}\keyword{array}\keyword{list}