subset
Subsetting Vectors, Matrices and Data Frames

Description

Subsets parts of elements, rows, and columns from vectors, matrices, or data frames.

Usage

subset(x, ...)
subset.default(x, subset, ...)
subset.matrix(x, subset, select, drop = FALSE, ...)
subset.data.frame(x, subset, select, drop = FALSE, ...)

Arguments

x the object to subset.
subset a logical expression. Indicates which elements (from a vector or a matrix) or which rows (from a data frame) to subset.
select an expression that indicates which columns to select. It is used only for a matrix or a data frame.
drop a logical flag that is passed to the index operator [ to determine the class and shape of the extracted result. See the drop details in Subscript for more information.
... further arguments to be passed to or from other methods.

Details

subset is generic function and has some S3 methods for the classes data.frame, matrix and vector(default).
Value
returns an object similar to x, which contains selected elements, rows, and columns, from vectors, matrices or data frames.
Note
The argument subset is evaluated in the data frame, so columns can be referred by name as variables in the expression.
See Also
Subscript, Extract
Examples
x <- runif(20)
subset(x, x > 0.3 & x < 0.7)   

z <- matrix(1:16, nrow=4) subset(z, z[,3]==10) # [,1] [,2] [,3] [,4] # [1,] 2 6 10 14 subset(z, z[,3]==10, drop=TRUE) # [1] 2 6 10 14

y <- matrix(c(2, 4, 3, 9, 21, NA, 6, 4, 9, 10, NA, 7), nrow = 3) dimnames(y)<-list(c("r1","r2","r3"), c("c1","c2","c3","c4")) subset(y, y[,4] > 8) subset(y, !is.na(y[,4]),select = c(2:4))

df <- data.frame(aa=1:10, bb=LETTERS[1:10], cc=letters[rep(1:5,2)]) subset(df, cc=="b") # aa bb cc # 2 2 B b # 7 7 G b subset(df, cc=="b" & aa>5) # aa bb cc # 7 7 G b subset(df, cc=="b" & aa>5, select=c("aa","cc")) # aa cc # 7 7 b

Package base version 6.1.1-7
Package Index