The R Project SVN R

Rev

Rev 90070 | 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
68948 ripley 2
% Part of the R package, https://www.R-project.org
90069 maechler 3
% Copyright 1995-2026 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}
76057 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{
90069 maechler 15
  Extract or replace subsets of data frames (to replace subsets is also
90081 hornik 16
  called \sQuote{to \I{subassign}}).
24767 ripley 17
}
18
\usage{
42283 hornik 19
\method{[}{data.frame}(x, i, j, drop = )
20
\method{[}{data.frame}(x, i, j) <- value
42981 ripley 21
\method{[[}{data.frame}(x, ..., exact = TRUE)
42283 hornik 22
\method{[[}{data.frame}(x, i, j) <- value
76064 maechler 23
% \method{$}{data.frame}(x, name)
48668 ripley 24
\method{$}{data.frame}(x, name) <- value
24767 ripley 25
}
26
\arguments{
27
  \item{x}{data frame.}
31067 ripley 28
 
42283 hornik 29
  \item{i, j, ...}{elements to extract or replace.  For \code{[} and
30
    \code{[[}, these are \code{numeric} or \code{character} or, for
79013 kalibera 31
    \code{[} only, empty or \code{logical}.  Numeric values are coerced to integer as if
42283 hornik 32
    by \code{\link{as.integer}}.  For replacement by \code{[}, a logical
48668 ripley 33
    matrix is allowed.}
24855 ripley 34
 
48668 ripley 35
  \item{name}{
85065 smeyer 36
    a literal character string or a \link{name} (possibly \link{backtick}
48668 ripley 37
    quoted).}
38
 
24767 ripley 39
  \item{drop}{logical.  If \code{TRUE} the result is coerced to the
39244 ripley 40
    lowest possible dimension.  The default is to drop if only one
41
    column is left, but \bold{not} to drop if only one row is left.}
24855 ripley 42
 
85065 smeyer 43
  \item{value}{a suitable replacement value: it will be repeated a whole
24811 ripley 44
    number of times if necessary and it may be coerced: see the
24878 ripley 45
    Coercion section.  If \code{NULL}, deletes the column if a single
46
    column is selected.}
42975 ripley 47
 
48
   \item{exact}{logical: see \code{\link{[}}, and applies to column names.}
24767 ripley 49
}
50
\details{
51
  Data frames can be indexed in several modes.  When \code{[} and
61433 ripley 52
  \code{[[} are used with a single vector index (\code{x[i]} or
59304 murdoch 53
  \code{x[[i]]}), they index the data frame as if it were a list.  In
54
  this usage a \code{drop} argument is ignored, with a warning.
24767 ripley 55
 
76103 maechler 56
  There is no \code{data.frame} method for \code{$}, so \code{x$name}
76118 maechler 57
  uses the default method which treats \code{x} as a list (with partial
58
  matching of column names if the match is unique, see
59
  \code{\link{Extract}}).  The replacement method (for \code{$}) checks
76103 maechler 60
  \code{value} for the correct number of rows, and replicates it if 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
66444 hornik 72
  names will be transformed to be unique if necessary (e.g., if columns
46715 ripley 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.
90069 maechler 107
 
90081 hornik 108
  When the replacement methods are used to \I{subassign} into a column vector,
90069 maechler 109
  the vector elements assigned into must correspond to existing rows in the
90081 hornik 110
  data frame.  If \I{subassignment} is used to add a non-existing column, the
90069 maechler 111
  column will be added as described above, with unassigned elements set
90070 smeyer 112
  to \code{NA}, see \manual{R-lang}{Subset assignment} for a rationale.
24767 ripley 113
}
24811 ripley 114
\section{Coercion}{
115
  The story over when replacement values are coerced is a complicated
116
  one, and one that has changed during \R's development.  This section
24825 ripley 117
  is a guide only.
24811 ripley 118
 
24855 ripley 119
  When \code{[} and \code{[[} are used to add or replace a whole column,
120
  no coercion takes place but \code{value} will be
24825 ripley 121
  replicated (by calling the generic function \code{\link{rep}}) to the
122
  right length if an exact number of repeats can be used.
24811 ripley 123
 
124
  When \code{[} is used with a logical matrix, each value is coerced to
41588 ripley 125
  the type of the column into which it is to be placed.
24811 ripley 126
 
24855 ripley 127
  When  \code{[} and \code{[[} are used with two indices, the
24889 ripley 128
  column will be coerced as necessary to accommodate the value.
27928 ripley 129
 
130
  Note that when the replacement value is an array (including a matrix)
131
  it is \emph{not} treated as a series of columns (as
132
  \code{\link{data.frame}} and \code{\link{as.data.frame}} do) but
133
  inserted as a single column.
24811 ripley 134
}
24767 ripley 135
\section{Warning}{
39244 ripley 136
  The default behaviour when only one \emph{row} is left is equivalent to
24889 ripley 137
  specifying \code{drop = FALSE}.  To drop from a data frame to a list,
33933 ripley 138
  \code{drop = TRUE} has to be specified explicitly.
48645 ripley 139
 
48681 ripley 140
  Arguments other than \code{drop} and \code{exact} should not be named:
141
  there is a warning if they are and the behaviour differs from the
52674 maechler 142
  description here.
24767 ripley 143
}
144
\value{
24855 ripley 145
  For \code{[} a data frame, list or a single column (the latter two
146
  only when dimensions have been dropped).  If matrix indexing is used for
62007 maechler 147
  extraction a vector results.  If the result would be a data frame an
42415 ripley 148
  error results if undefined columns are selected (as there is no general
149
  concept of a 'missing' column in a data frame).  Otherwise if a single
150
  column is selected and this is undefined the result is \code{NULL}.
24767 ripley 151
 
42415 ripley 152
  For \code{[[} a column of the data frame or \code{NULL}
153
  (extraction with one index)
24855 ripley 154
  or a length-one vector (extraction with two indices).
155
 
42415 ripley 156
  For \code{$}, a column of the data frame (or \code{NULL}).
157
 
24889 ripley 158
  For \code{[<-}, \code{[[<-} and \code{$<-}, a data frame.
24767 ripley 159
}
160
\seealso{
25898 maechler 161
  \code{\link{subset}} which is often easier for extraction,
162
  \code{\link{data.frame}}, \code{\link{Extract}}.
24767 ripley 163
}
164
\examples{
165
sw <- swiss[1:5, 1:4]  # select a manageable subset
166
 
167
sw[1:3]      # select columns
168
sw[, 1:3]    # same
169
sw[4:5, 1:3] # select rows and columns
170
sw[1]        # a one-column data frame
171
sw[, 1, drop = FALSE]  # the same
27625 ripley 172
sw[, 1]      # a (unnamed) vector
24767 ripley 173
sw[[1]]      # the same
76118 maechler 174
sw$Fert      # the same (possibly w/ warning, see ?Extract)
24767 ripley 175
 
176
sw[1,]       # a one-row data frame
61150 ripley 177
sw[1,, drop = TRUE]  # a list
43550 ripley 178
 
179
sw["C", ] # partially matches
180
sw[match("C", row.names(sw)), ] # no exact match
52674 maechler 181
try(sw[, "Ferti"]) # column names must match exactly
43550 ripley 182
 
40206 maechler 183
\dontshow{
61168 ripley 184
stopifnot(identical(sw[, 1], sw[[1]]),
185
          identical(sw[, 1][1], 80.2),
186
          identical(sw[, 1, drop = FALSE], sw[1]),
71438 ripley 187
          is.data.frame(sw[1 ]), dim(sw[1 ]) == c(5, 1),
188
          is.data.frame(sw[1,]), dim(sw[1,]) == c(1, 4),
61168 ripley 189
          is.list(s1 <- sw[1, , drop = TRUE]), identical(s1$Fertility, 80.2))
71139 maechler 190
tools::assertError(sw[, "Ferti"])
40206 maechler 191
}
79013 kalibera 192
sw[sw$Fertility > 90,] # logical indexing, see also ?subset
193
sw[c(1, 1:2), ]        # duplicate row, unique row names are created
24767 ripley 194
 
195
sw[sw <= 6] <- 6  # logical matrix indexing
196
sw
24811 ripley 197
 
198
## adding a column
199
sw["new1"] <- LETTERS[1:5]   # adds a character column
200
sw[["new2"]] <- letters[1:5] # ditto
24855 ripley 201
sw[, "new3"] <- LETTERS[1:5] # ditto
24878 ripley 202
sw$new4 <- 1:5
24811 ripley 203
sapply(sw, class)
76118 maechler 204
sw$new  # -> NULL: no unique partial match
24878 ripley 205
sw$new4 <- NULL              # delete the column
24889 ripley 206
sw
61150 ripley 207
sw[6:8] <- list(letters[10:14], NULL, aa = 1:5)
52674 maechler 208
# update col. 6, delete 7, append
24889 ripley 209
sw
24811 ripley 210
 
24855 ripley 211
## matrices in a data frame
71139 maechler 212
A <- data.frame(x = 1:3, y = I(matrix(4:9, 3, 2)),
213
                         z = I(matrix(letters[1:9], 3, 3)))
38402 ripley 214
A[1:3, "y"] # a matrix
25898 maechler 215
A[1:3, "z"] # a matrix
24855 ripley 216
A[, "y"]    # a matrix
71139 maechler 217
stopifnot(identical(colnames(A), c("x", "y", "z")), ncol(A) == 3L,
218
          identical(A[,"y"], A[1:3, "y"]),
219
          inherits (A[,"y"], "AsIs"))
52676 maechler 220
 
221
## keeping special attributes: use a class with a
71139 maechler 222
## "as.data.frame" and "[" method;
223
## "avector" := vector that keeps attributes.   Could provide a constructor
224
##  avector <- function(x) { class(x) <- c("avector", class(x)); x }
52676 maechler 225
as.data.frame.avector <- as.data.frame.vector
226
 
227
`[.avector` <- function(x,i,...) {
228
  r <- NextMethod("[")
229
  mostattributes(r) <- attributes(x)
230
  r
24855 ripley 231
}
52676 maechler 232
 
61150 ripley 233
d <- data.frame(i = 0:7, f = gl(2,4),
234
                u = structure(11:18, unit = "kg", class = "avector"))
52676 maechler 235
str(d[2:4, -1]) # 'u' keeps its "unit"
236
\dontshow{
237
stopifnot(identical(d[2:4,-1][,"u"],
61150 ripley 238
                    structure(12:14, unit = "kg", class = "avector")))
52676 maechler 239
}
240
}
24767 ripley 241
\keyword{array}