select: Select rows or columns from data frames or matrices while...

Description Usage Arguments Details Value Author(s) Examples

View source: R/select.R

Description

The primary contribution of this function is that if a single row or column is selected, the object that is returned will be a matrix or a dataframe—and it will not be collapsed into a single vector, as is the usual behavior in R.

Usage

1
select(data, selection, cols = TRUE)

Arguments

data

A matrix or dataframe from whence data will be selected

selection

A character vector with column (or row) names, or, a numeric vector with column (or row) indexes.

cols

A logical, that when TRUE, indicates that columns will be selected. If FALSE, rows will be selected.

Details

Selecting no rows or no columns is possible if selection = 0 or if length(selection) == 0. In this case, a data frame or matrix with either 0 columns or 0 rows is returned.

Value

The matrix or data frame is returned with the selected columns or rows.

Author(s)

Landon Sego

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# Consider this data frame
d <- data.frame(a = 1:5, b = rnorm(5), c = letters[1:5], d = factor(6:10),
                row.names = LETTERS[1:5], stringsAsFactors = FALSE)

# We get identical behavior when selecting more than one column
d1 <- d[, c("d", "c")]
d1c <- select(d, c("d", "c"))
d1
d1c
identical(d1, d1c)

# Different behavior when selecting a single column
d[,"a"]
select(d, "a")

# We can also select using numeric indexes
select(d, 1)

# Selecting a single row from a data frame produces results identical to default R behavior
d2 <- d[2,]
d2c <- select(d, "B", cols = FALSE)
identical(d2, d2c)

# Now consider a matrix
m <- matrix(rnorm(20), nrow = 4, dimnames = list(LETTERS[1:4], letters[1:5]))

# Column selection with two or more or more columns is equivalent to default R behavior
m1 <- m[,c(4, 3)]
m1c <- select(m, c("d", "c"))
m1
m1c
identical(m1, m1c)

# Selecting a single column returns a matrix of 1 column instead of a vector
m[,2]
select(m, 2)

# Selecting a single row returns a matrix of 1 row instead of a vector
m2 <- m["C",]
m2c <- select(m, "C", cols = FALSE)
m2
m2c
is.matrix(m2)
is.matrix(m2c)

# Selecting no rows or no columns occurs if 0 or an object of length 0
# is passed to 'selection'
select(d, 0)
select(d, which("bizarre" %in% colnames(d)))
select(d, 0, cols = FALSE)

Smisc documentation built on May 2, 2019, 2:46 a.m.