Subsetting
There are a number of operators that can be used to extract subsets of R objects.
- [ always returns an object of the same class as the original; can be used to select more than one element (there is one exception)
- [[ is used to extract elements of a list or a data frame; it can only be used to extract a single element and the class of the returned object will not necessarily be a list or data frame
- $ is used to extract elements of a list or data frame by name; semantics(语义) are similar to that of [[.
subsetting vector
前三个属于数字索引,后三个是逻辑索引。
Subsetting Lists
The [[ operator can be used with computed indices(计算指令); $ can only be used with literal names.(字面名称)
The [[ can take an integer sequence.
Subsetting a Matrix
Matrices can be subsetted in the usual way with (i,j) type indices.
By default, when a single element of a matrix is retrieved, it is returned as a vector of length 1 rather than a 1 × 1 matrix. This behavior can be turned off by setting drop = FALSE.
Partial Matching (模糊匹配)
Partial matching of names is allowed with [[ and $.
Removing NA Values
A common task is to remove missing values (NAs).
(1)移除单一对象中的缺失值
(2)移除多个对象中的缺失值,使用complete.cases函数。