The R Project SVN R

Rev

Rev 62333 | Rev 67599 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
42333 ripley 1
% File src/library/base/man/Extract.data.frame.Rd
2
% Part of the R package, http://www.R-project.org
62007 maechler 3
% Copyright 1995-2013 R Core Team
42333 ripley 4
% Distributed under GPL 2 or later
5
 
24767 ripley 6
\name{Extract.data.frame}
7
\alias{[.data.frame}
8
\alias{[[.data.frame}
9
\alias{[<-.data.frame}
10
\alias{[[<-.data.frame}
62333 pd 11
\alias{$.data.frame}
24878 ripley 12
\alias{$<-.data.frame}
24767 ripley 13
\title{Extract or Replace Parts of a Data Frame}
14
\description{
15
  Extract or replace subsets of data frames.
16
}
17
\usage{
42283 hornik 18
\method{[}{data.frame}(x, i, j, drop = )
19
\method{[}{data.frame}(x, i, j) <- value
42981 ripley 20
\method{[[}{data.frame}(x, ..., exact = TRUE)
42283 hornik 21
\method{[[}{data.frame}(x, i, j) <- value
62333 pd 22
\method{$}{data.frame}(x, name)
48668 ripley 23
\method{$}{data.frame}(x, name) <- value
24767 ripley 24
}
25
\arguments{
26
  \item{x}{data frame.}
31067 ripley 27
 
42283 hornik 28
  \item{i, j, ...}{elements to extract or replace.  For \code{[} and
29
    \code{[[}, these are \code{numeric} or \code{character} or, for
30
    \code{[} only, empty.  Numeric values are coerced to integer as if
31
    by \code{\link{as.integer}}.  For replacement by \code{[}, a logical
48668 ripley 32
    matrix is allowed.}
24855 ripley 33
 
48668 ripley 34
  \item{name}{
35
    A literal character string or a \link{name} (possibly \link{backtick}
36
    quoted).}
37
 
24767 ripley 38
  \item{drop}{logical.  If \code{TRUE} the result is coerced to the
39244 ripley 39
    lowest possible dimension.  The default is to drop if only one
40
    column is left, but \bold{not} to drop if only one row is left.}
24855 ripley 41
 
24767 ripley 42
  \item{value}{A suitable replacement value: it will be repeated a whole
24811 ripley 43
    number of times if necessary and it may be coerced: see the
24878 ripley 44
    Coercion section.  If \code{NULL}, deletes the column if a single
45
    column is selected.}
42975 ripley 46
 
47
   \item{exact}{logical: see \code{\link{[}}, and applies to column names.}
24767 ripley 48
}
49
\details{
50
  Data frames can be indexed in several modes.  When \code{[} and
61433 ripley 51
  \code{[[} are used with a single vector index (\code{x[i]} or
59304 murdoch 52
  \code{x[[i]]}), they index the data frame as if it were a list.  In
53
  this usage a \code{drop} argument is ignored, with a warning.
24767 ripley 54
 
62333 pd 55
  The \code{data.frame} method for \code{$}, treats \code{x} as a
56
  list, except that (as of R-3.1.0) partial matching of \code{name} to
57
  the names of \code{x} will generate a warning; this may become an
58
  error in future versions.  The replacement method checks
59
  \code{value} for the correct number of rows, and replicates it if
60
  necessary.
48668 ripley 61
 
42283 hornik 62
  When \code{[} and \code{[[} are used with two indices (\code{x[i, j]}
63
  and \code{x[[i, j]]}) they act like indexing a matrix:  \code{[[} can
52676 maechler 64
  only be used to select one element.  Note that for each selected
65
  column, \code{xj} say, typically (if it is not matrix-like), the
66
  resulting column will be \code{xj[i]}, and hence rely on the
67
  corresponding \code{[} method, see the examples section.
24767 ripley 68
 
24855 ripley 69
  If \code{[} returns a data frame it will have unique (and non-missing)
70
  row names, if necessary transforming the row names using
46715 ripley 71
  \code{\link{make.unique}}.  Similarly, if columns are selected column
72
  names will be transformed to be unique if necessary (e.g. if columns
73
  are selected more than once, or if more than one column of a given
51173 ripley 74
  name is selected if the data frame has duplicate column names).
24767 ripley 75
 
42283 hornik 76
  When \code{drop = TRUE}, this is applied to the subsetting of any
24855 ripley 77
  matrices contained in the data frame as well as to the data frame itself.
78
 
24767 ripley 79
  The replacement methods can be used to add whole column(s) by specifying
80
  non-existent column(s), in which case the column(s) are added at the
81
  right-hand edge of the data frame and numerical indices must be
24855 ripley 82
  contiguous to existing indices.  On the other hand, rows can be added
83
  at any row after the current last row, and the columns will be
31073 ripley 84
  in-filled with missing values.  Missing values in the indices are not
85
  allowed for replacement.
24767 ripley 86
 
24889 ripley 87
  For \code{[} the replacement value can be a list: each element of the
88
  list is used to replace (part of) one column, recycling the list as
34636 ripley 89
  necessary.  If columns specified by number are created, the names
24889 ripley 90
  (if any) of the corresponding list elements are used to name the
27625 ripley 91
  columns.  If the replacement is not selecting rows, list values can
24889 ripley 92
  contain \code{NULL} elements which will cause the corresponding
34636 ripley 93
  columns to be deleted.  (See the Examples.)
24889 ripley 94
 
52674 maechler 95
  Matrix indexing (\code{x[i]} with a logical or a 2-column integer
59304 murdoch 96
  matrix \code{i}) using \code{[} is not recommended.  For extraction,
97
  \code{x} is first coerced to a matrix. For replacement, logical
98
  matrix indices must be of the same dimension as \code{x}.
99
  Replacements are done one column at a time, with multiple type
100
  coercions possibly taking place.
42971 ripley 101
 
102
  Both \code{[} and \code{[[} extraction methods partially match row
62341 ripley 103
  names.  By default neither partially match column names, but \code{[[}
104
  will if \code{exact = FALSE} (and with a warning if \code{exact =
105
  NA}).  If you want to exact matching on row names use
106
  \code{\link{match}}, as in the examples.
24767 ripley 107
}
24811 ripley 108
\section{Coercion}{
109
  The story over when replacement values are coerced is a complicated
110
  one, and one that has changed during \R's development.  This section
24825 ripley 111
  is a guide only.
24811 ripley 112
 
24855 ripley 113
  When \code{[} and \code{[[} are used to add or replace a whole column,
114
  no coercion takes place but \code{value} will be
24825 ripley 115
  replicated (by calling the generic function \code{\link{rep}}) to the
116
  right length if an exact number of repeats can be used.
24811 ripley 117
 
118
  When \code{[} is used with a logical matrix, each value is coerced to
41588 ripley 119
  the type of the column into which it is to be placed.
24811 ripley 120
 
24855 ripley 121
  When  \code{[} and \code{[[} are used with two indices, the
24889 ripley 122
  column will be coerced as necessary to accommodate the value.
27928 ripley 123
 
124
  Note that when the replacement value is an array (including a matrix)
125
  it is \emph{not} treated as a series of columns (as
126
  \code{\link{data.frame}} and \code{\link{as.data.frame}} do) but
127
  inserted as a single column.
24811 ripley 128
}
24767 ripley 129
\section{Warning}{
39244 ripley 130
  The default behaviour when only one \emph{row} is left is equivalent to
24889 ripley 131
  specifying \code{drop = FALSE}.  To drop from a data frame to a list,
33933 ripley 132
  \code{drop = TRUE} has to be specified explicitly.
48645 ripley 133
 
48681 ripley 134
  Arguments other than \code{drop} and \code{exact} should not be named:
135
  there is a warning if they are and the behaviour differs from the
52674 maechler 136
  description here.
24767 ripley 137
}
138
\value{
24855 ripley 139
  For \code{[} a data frame, list or a single column (the latter two
140
  only when dimensions have been dropped).  If matrix indexing is used for
62007 maechler 141
  extraction a vector results.  If the result would be a data frame an
42415 ripley 142
  error results if undefined columns are selected (as there is no general
143
  concept of a 'missing' column in a data frame).  Otherwise if a single
144
  column is selected and this is undefined the result is \code{NULL}.
24767 ripley 145
 
42415 ripley 146
  For \code{[[} a column of the data frame or \code{NULL}
147
  (extraction with one index)
24855 ripley 148
  or a length-one vector (extraction with two indices).
149
 
42415 ripley 150
  For \code{$}, a column of the data frame (or \code{NULL}).
151
 
24889 ripley 152
  For \code{[<-}, \code{[[<-} and \code{$<-}, a data frame.
24767 ripley 153
}
154
\seealso{
25898 maechler 155
  \code{\link{subset}} which is often easier for extraction,
156
  \code{\link{data.frame}}, \code{\link{Extract}}.
24767 ripley 157
}
158
\examples{
159
sw <- swiss[1:5, 1:4]  # select a manageable subset
160
 
161
sw[1:3]      # select columns
162
sw[, 1:3]    # same
163
sw[4:5, 1:3] # select rows and columns
164
sw[1]        # a one-column data frame
165
sw[, 1, drop = FALSE]  # the same
27625 ripley 166
sw[, 1]      # a (unnamed) vector
24767 ripley 167
sw[[1]]      # the same
168
 
169
sw[1,]       # a one-row data frame
61150 ripley 170
sw[1,, drop = TRUE]  # a list
43550 ripley 171
 
172
sw["C", ] # partially matches
173
sw[match("C", row.names(sw)), ] # no exact match
52674 maechler 174
try(sw[, "Ferti"]) # column names must match exactly
43550 ripley 175
 
40206 maechler 176
\dontshow{
61168 ripley 177
stopifnot(identical(sw[, 1], sw[[1]]),
178
          identical(sw[, 1][1], 80.2),
179
          identical(sw[, 1, drop = FALSE], sw[1]),
40206 maechler 180
          is.data.frame(sw[1]), dim(sw[1] ) == c(5,1),
61168 ripley 181
          is.data.frame(sw[1,]), dim(sw[1,]) == c(1,4),
182
          is.list(s1 <- sw[1, , drop = TRUE]), identical(s1$Fertility, 80.2))
40206 maechler 183
}
24767 ripley 184
swiss[ c(1, 1:2), ]   # duplicate row, unique row names are created
185
 
186
sw[sw <= 6] <- 6  # logical matrix indexing
187
sw
24811 ripley 188
 
189
## adding a column
190
sw["new1"] <- LETTERS[1:5]   # adds a character column
191
sw[["new2"]] <- letters[1:5] # ditto
24855 ripley 192
sw[, "new3"] <- LETTERS[1:5] # ditto
24878 ripley 193
sw$new4 <- 1:5
24811 ripley 194
sapply(sw, class)
24878 ripley 195
sw$new4 <- NULL              # delete the column
24889 ripley 196
sw
61150 ripley 197
sw[6:8] <- list(letters[10:14], NULL, aa = 1:5)
52674 maechler 198
# update col. 6, delete 7, append
24889 ripley 199
sw
24811 ripley 200
 
24855 ripley 201
## matrices in a data frame
61150 ripley 202
A <- data.frame(x = 1:3, y = I(matrix(4:6)), z = I(matrix(letters[1:9], 3, 3)))
38402 ripley 203
A[1:3, "y"] # a matrix
25898 maechler 204
A[1:3, "z"] # a matrix
24855 ripley 205
A[, "y"]    # a matrix
52676 maechler 206
 
207
## keeping special attributes: use a class with a
208
## "as.data.frame" and "[" method:
209
% "avector" := vector that keeps attributes and we could provide a constructor
210
%  avector <- function(x) { class(x) <- c("avector", class(x)); x }
211
as.data.frame.avector <- as.data.frame.vector
212
 
213
`[.avector` <- function(x,i,...) {
214
  r <- NextMethod("[")
215
  mostattributes(r) <- attributes(x)
216
  r
24855 ripley 217
}
52676 maechler 218
 
61150 ripley 219
d <- data.frame(i = 0:7, f = gl(2,4),
220
                u = structure(11:18, unit = "kg", class = "avector"))
52676 maechler 221
str(d[2:4, -1]) # 'u' keeps its "unit"
222
\dontshow{
223
stopifnot(identical(d[2:4,-1][,"u"],
61150 ripley 224
                    structure(12:14, unit = "kg", class = "avector")))
52676 maechler 225
}
226
}
24767 ripley 227
\keyword{array}