as: Force an Object to Belong to a Class

Description Usage Arguments Value list tibble References See Also Examples

Description

Coerce an object to a given class.

Usage

1
2
3
4
5
6
7
as.DataFrame(x)

as.SummarizedExperiment(x)

## S4 method for signature 'sparseMatrix'
as.data.frame(x, row.names = NULL,
  optional = FALSE, ...)

Arguments

x

Object.

row.names

See base::as.data.frame for details.

optional

See base::as.data.frame for details.

...

Additional arguments.

Value

Object of new class.

list

It is often useful to coerce an S4 object to a flat list for archival storage. Here we are providing the coerceS4ToList() function, which consistently coerces the slots in any S4 to a standard list. Additionally, here we have improved support for SummarizedExperiment to list coercion, returning the slots as a list.

tibble

Coerce an object to a tibble (tbl_df, data.frame) using either S3 or S4 methods:

Tibbles don't support row name assignment, so here we are ensuring they are kept by moving them to a column named rowname by default. This helps avoid downstream unexpected data loss when using the dplyr chain of single table verbs, such as dplyr::arrange(), dplyr::filter(), or dplyr::mutate().

This behavior can be overriden in the S3 method by setting rowname = NULL instead, which is the current default in the tibble package. The S4 coercion method doesn't support arguments, and therefore always attempts to move rownames automatically, if defined.

Conversely, when coercing a tibble back to an S4 DataFrame, our as(tbl_df, Class = "DataFrame") method looks for the rowname column and will attempt to move it back to base::rownames() automatically, unless there are duplicates present.

References

Chambers, John M. (2016) Extending R, Chapman & Hall. (Chapters 9 and 10.)

See Also

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
data(rse, package = "basejump.data")

## DataFrame to tbl_df ====
data <- SummarizedExperiment::colData(rse)
print(data)

x <- as(data, "tbl_df")
print(x)

x <- as_tibble(data)
print(x)

## GRanges to tbl_df ====
data <- SummarizedExperiment::rowRanges(rse)

x <- as(data, "tbl_df")

x <- as_tibble(data)
colnames(x)

## sparseMatrix to data.frame ====
data(sparse, package = "basejump.data")

x <- as.data.frame(sparse)
class(x)

x <- as(sparse, "data.frame")
class(x)

## tbl_df to DataFrame ====
data <- as_tibble(datasets::iris)

x <- as(data, "DataFrame")

steinbaugh/basejump.coercion documentation built on Nov. 5, 2018, 10:38 p.m.