The R Project SVN R

Rev

Rev 76103 | Rev 85065 | 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
68948 ripley 2
% Part of the R package, https://www.R-project.org
76064 maechler 3
% Copyright 1995-2019 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{
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
76064 maechler 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
 
76103 maechler 55
  There is no \code{data.frame} method for \code{$}, so \code{x$name}
76118 maechler 56
  uses the default method which treats \code{x} as a list (with partial
57
  matching of column names if the match is unique, see
58
  \code{\link{Extract}}).  The replacement method (for \code{$}) checks
76103 maechler 59
  \code{value} for the correct number of rows, and replicates it if necessary.
48668 ripley 60
 
42283 hornik 61
  When \code{[} and \code{[[} are used with two indices (\code{x[i, j]}
62
  and \code{x[[i, j]]}) they act like indexing a matrix:  \code{[[} can
52676 maechler 63
  only be used to select one element.  Note that for each selected
64
  column, \code{xj} say, typically (if it is not matrix-like), the
65
  resulting column will be \code{xj[i]}, and hence rely on the
66
  corresponding \code{[} method, see the examples section.
24767 ripley 67
 
24855 ripley 68
  If \code{[} returns a data frame it will have unique (and non-missing)
69
  row names, if necessary transforming the row names using
46715 ripley 70
  \code{\link{make.unique}}.  Similarly, if columns are selected column
66444 hornik 71
  names will be transformed to be unique if necessary (e.g., if columns
46715 ripley 72
  are selected more than once, or if more than one column of a given
51173 ripley 73
  name is selected if the data frame has duplicate column names).
24767 ripley 74
 
42283 hornik 75
  When \code{drop = TRUE}, this is applied to the subsetting of any
24855 ripley 76
  matrices contained in the data frame as well as to the data frame itself.
77
 
24767 ripley 78
  The replacement methods can be used to add whole column(s) by specifying
79
  non-existent column(s), in which case the column(s) are added at the
80
  right-hand edge of the data frame and numerical indices must be
24855 ripley 81
  contiguous to existing indices.  On the other hand, rows can be added
82
  at any row after the current last row, and the columns will be
31073 ripley 83
  in-filled with missing values.  Missing values in the indices are not
84
  allowed for replacement.
24767 ripley 85
 
24889 ripley 86
  For \code{[} the replacement value can be a list: each element of the
87
  list is used to replace (part of) one column, recycling the list as
34636 ripley 88
  necessary.  If columns specified by number are created, the names
24889 ripley 89
  (if any) of the corresponding list elements are used to name the
27625 ripley 90
  columns.  If the replacement is not selecting rows, list values can
24889 ripley 91
  contain \code{NULL} elements which will cause the corresponding
34636 ripley 92
  columns to be deleted.  (See the Examples.)
24889 ripley 93
 
52674 maechler 94
  Matrix indexing (\code{x[i]} with a logical or a 2-column integer
59304 murdoch 95
  matrix \code{i}) using \code{[} is not recommended.  For extraction,
96
  \code{x} is first coerced to a matrix. For replacement, logical
97
  matrix indices must be of the same dimension as \code{x}.
98
  Replacements are done one column at a time, with multiple type
99
  coercions possibly taking place.
42971 ripley 100
 
101
  Both \code{[} and \code{[[} extraction methods partially match row
62341 ripley 102
  names.  By default neither partially match column names, but \code{[[}
103
  will if \code{exact = FALSE} (and with a warning if \code{exact =
104
  NA}).  If you want to exact matching on row names use
105
  \code{\link{match}}, as in the examples.
24767 ripley 106
}
24811 ripley 107
\section{Coercion}{
108
  The story over when replacement values are coerced is a complicated
109
  one, and one that has changed during \R's development.  This section
24825 ripley 110
  is a guide only.
24811 ripley 111
 
24855 ripley 112
  When \code{[} and \code{[[} are used to add or replace a whole column,
113
  no coercion takes place but \code{value} will be
24825 ripley 114
  replicated (by calling the generic function \code{\link{rep}}) to the
115
  right length if an exact number of repeats can be used.
24811 ripley 116
 
117
  When \code{[} is used with a logical matrix, each value is coerced to
41588 ripley 118
  the type of the column into which it is to be placed.
24811 ripley 119
 
24855 ripley 120
  When  \code{[} and \code{[[} are used with two indices, the
24889 ripley 121
  column will be coerced as necessary to accommodate the value.
27928 ripley 122
 
123
  Note that when the replacement value is an array (including a matrix)
124
  it is \emph{not} treated as a series of columns (as
125
  \code{\link{data.frame}} and \code{\link{as.data.frame}} do) but
126
  inserted as a single column.
24811 ripley 127
}
24767 ripley 128
\section{Warning}{
39244 ripley 129
  The default behaviour when only one \emph{row} is left is equivalent to
24889 ripley 130
  specifying \code{drop = FALSE}.  To drop from a data frame to a list,
33933 ripley 131
  \code{drop = TRUE} has to be specified explicitly.
48645 ripley 132
 
48681 ripley 133
  Arguments other than \code{drop} and \code{exact} should not be named:
134
  there is a warning if they are and the behaviour differs from the
52674 maechler 135
  description here.
24767 ripley 136
}
137
\value{
24855 ripley 138
  For \code{[} a data frame, list or a single column (the latter two
139
  only when dimensions have been dropped).  If matrix indexing is used for
62007 maechler 140
  extraction a vector results.  If the result would be a data frame an
42415 ripley 141
  error results if undefined columns are selected (as there is no general
142
  concept of a 'missing' column in a data frame).  Otherwise if a single
143
  column is selected and this is undefined the result is \code{NULL}.
24767 ripley 144
 
42415 ripley 145
  For \code{[[} a column of the data frame or \code{NULL}
146
  (extraction with one index)
24855 ripley 147
  or a length-one vector (extraction with two indices).
148
 
42415 ripley 149
  For \code{$}, a column of the data frame (or \code{NULL}).
150
 
24889 ripley 151
  For \code{[<-}, \code{[[<-} and \code{$<-}, a data frame.
24767 ripley 152
}
153
\seealso{
25898 maechler 154
  \code{\link{subset}} which is often easier for extraction,
155
  \code{\link{data.frame}}, \code{\link{Extract}}.
24767 ripley 156
}
157
\examples{
158
sw <- swiss[1:5, 1:4]  # select a manageable subset
159
 
160
sw[1:3]      # select columns
161
sw[, 1:3]    # same
162
sw[4:5, 1:3] # select rows and columns
163
sw[1]        # a one-column data frame
164
sw[, 1, drop = FALSE]  # the same
27625 ripley 165
sw[, 1]      # a (unnamed) vector
24767 ripley 166
sw[[1]]      # the same
76118 maechler 167
sw$Fert      # the same (possibly w/ warning, see ?Extract)
24767 ripley 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]),
71438 ripley 180
          is.data.frame(sw[1 ]), dim(sw[1 ]) == c(5, 1),
181
          is.data.frame(sw[1,]), dim(sw[1,]) == c(1, 4),
61168 ripley 182
          is.list(s1 <- sw[1, , drop = TRUE]), identical(s1$Fertility, 80.2))
71139 maechler 183
tools::assertError(sw[, "Ferti"])
40206 maechler 184
}
24767 ripley 185
swiss[ c(1, 1:2), ]   # duplicate row, unique row names are created
186
 
187
sw[sw <= 6] <- 6  # logical matrix indexing
188
sw
24811 ripley 189
 
190
## adding a column
191
sw["new1"] <- LETTERS[1:5]   # adds a character column
192
sw[["new2"]] <- letters[1:5] # ditto
24855 ripley 193
sw[, "new3"] <- LETTERS[1:5] # ditto
24878 ripley 194
sw$new4 <- 1:5
24811 ripley 195
sapply(sw, class)
76118 maechler 196
sw$new  # -> NULL: no unique partial match
24878 ripley 197
sw$new4 <- NULL              # delete the column
24889 ripley 198
sw
61150 ripley 199
sw[6:8] <- list(letters[10:14], NULL, aa = 1:5)
52674 maechler 200
# update col. 6, delete 7, append
24889 ripley 201
sw
24811 ripley 202
 
24855 ripley 203
## matrices in a data frame
71139 maechler 204
A <- data.frame(x = 1:3, y = I(matrix(4:9, 3, 2)),
205
                         z = I(matrix(letters[1:9], 3, 3)))
38402 ripley 206
A[1:3, "y"] # a matrix
25898 maechler 207
A[1:3, "z"] # a matrix
24855 ripley 208
A[, "y"]    # a matrix
71139 maechler 209
stopifnot(identical(colnames(A), c("x", "y", "z")), ncol(A) == 3L,
210
          identical(A[,"y"], A[1:3, "y"]),
211
          inherits (A[,"y"], "AsIs"))
52676 maechler 212
 
213
## keeping special attributes: use a class with a
71139 maechler 214
## "as.data.frame" and "[" method;
215
## "avector" := vector that keeps attributes.   Could provide a constructor
216
##  avector <- function(x) { class(x) <- c("avector", class(x)); x }
52676 maechler 217
as.data.frame.avector <- as.data.frame.vector
218
 
219
`[.avector` <- function(x,i,...) {
220
  r <- NextMethod("[")
221
  mostattributes(r) <- attributes(x)
222
  r
24855 ripley 223
}
52676 maechler 224
 
61150 ripley 225
d <- data.frame(i = 0:7, f = gl(2,4),
226
                u = structure(11:18, unit = "kg", class = "avector"))
52676 maechler 227
str(d[2:4, -1]) # 'u' keeps its "unit"
228
\dontshow{
229
stopifnot(identical(d[2:4,-1][,"u"],
61150 ripley 230
                    structure(12:14, unit = "kg", class = "avector")))
52676 maechler 231
}
232
}
24767 ripley 233
\keyword{array}