[go: up one dir, main page]

File: set_class.R

package info (click to toggle)
r-cran-rio 1.2.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,052 kB
  • sloc: makefile: 2
file content (52 lines) | stat: -rw-r--r-- 1,177 bytes parent folder | download | duplicates (2)
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
51
52
set_class <- function(x, class = NULL) {
    if (is.null(class)) {
        return(x)
    }

    if ("data.table" %in% class) {
        return(.ensure_data_table(x))
    }

    if (any(c("tibble", "tbl_df", "tbl") %in% class)) {
        return(.ensure_tibble(x))
    }

    if (any(c("arrow", "arrow_table") %in% class)) {
        ## because setclass can be used without import, must check again
        .check_pkg_availability("arrow")
        return(.ensure_arrow(x))
    }
    return(.ensure_data_frame(x))
}

.ensure_arrow <- function(x) {
    if (inherits(x, "ArrowTabular")) {
        return(x)
    }
    return(arrow::arrow_table(x))
}

.ensure_data_table <- function(x) {
    if (inherits(x, "data.table")) {
        return(x)
    }
    return(data.table::as.data.table(x))
}

.ensure_tibble <- function(x) {
    if (inherits(x, "tbl")) {
        return(x)
    }
    return(tibble::as_tibble(x))
}

.ensure_data_frame <- function(x) {
    out <- structure(x, class = "data.frame")
    if (nrow(out) == 0) {
        return(out)
    }
    if (!length(rownames(out))) {
        rownames(out) <- as.character(seq_len(length(out[, 1L, drop = TRUE])))
    }
    return(out)
}