Debian Codegraph @

R/glimpse.R

raw
1 #' Get a glimpse of your data
2 #'
3 #' @description
4 #' `glimpse()` is like a transposed version of `print()`:
5 #' columns run down the page, and data runs across.
6 #' This makes it possible to see every column in a data frame.
7 #' It's a little like [str()] applied to a data frame
8 #' but it tries to show you as much data as possible.
9 #' (And it always shows the underlying data, even when applied
10 #' to a remote data source.)
11 #'
12 #' See [format_glimpse()] for details on the formatting.
13 #'
14 #' @section S3 methods:
15 #' `glimpse` is an S3 generic with a customised method for `tbl`s and
16 #' `data.frames`, and a default method that calls [str()].
17 #'
18 #' @param x An object to glimpse at.
19 #' @param width Width of output: defaults to the setting of the
20 #' `width` [option][pillar_options] (if finite)
21 #' or the width of the console.
22 #' @param ... Unused, for extensibility.
23 #' @return x original x is (invisibly) returned, allowing `glimpse()` to be
24 #' used within a data pipe line.
25 #' @export
26 #' @examples
27 #' glimpse(mtcars)
28 #'
29 #' @examplesIf rlang::is_installed("nycflights13")
30 #' glimpse(nycflights13::flights)
31 #'
32 glimpse <- function(x, width = NULL, ...) {
33 UseMethod("glimpse")
34 }
35
36 #' @export
37 glimpse.tbl <- function(x, width = NULL, ...) {
38 if (!is.null(width) && !is.finite(width)) {
39 abort("`width` must be finite.")
40 }
41 width <- get_width_glimpse(width)
42
43 rows_total <- tbl_nrow(x)
44 cli::cat_line("Rows: ", big_mark(rows_total))
45
46 # Needed early because we don't have tbl_ncol() yet.
47 # This is an overestimate, but shouldn't be too expensive.
48 # Every type needs at least three characters: "x, "
49 rows <- as.integer(width / 3)
50 if (is.na(rows_total)) {
51 df <- as.data.frame(head(x, rows))
52 } else {
53 df <- df_head(x, rows)
54 }
55
56 cli::cat_line("Columns: ", big_mark(ncol(df)))
57
58 summary <- tbl_sum(x)
59 brief_summary <- summary[-1]
60
61 if (has_length(brief_summary)) {
62 cli::cat_line(names(brief_summary), ": ", brief_summary)
63 }
64
65 if (ncol(df) == 0) {
66 return(invisible(x))
67 }
68
69 var_types <- map_chr(map(df, new_pillar_type), format)
70 ticked_names <- format(new_pillar_title(tick_if_needed(names(df))))
71 var_names <- paste0("$ ", align(ticked_names), " ", var_types, " ")
72
73 # for some reason the offset was -2 in tibble but is now -1
74 # so that the desired width is obtained
75 data_width <- width - get_extent(var_names) - 1
76 formatted <- map_chr(df, format_glimpse_1)
77 truncated <- str_trunc(formatted, data_width)
78
79 cli::cat_line(var_names, truncated)
80 invisible(x)
81 }
82
83 #' @export
84 glimpse.data.frame <- glimpse.tbl
85
86 #' @importFrom utils str
87 #' @export
88 glimpse.default <- function(x, width = NULL, max.level = 3, ...) {
89 str(x, width = get_width_glimpse(width), max.level = max.level, ...)
90 invisible(x)
91 }
92
93 #' Format a vector for horizontal printing
94 #'
95 #' @description
96 #' `r lifecycle::badge("experimental")`
97 #'
98 #' This generic provides the logic for printing vectors in [glimpse()].
99 #'
100 #' The output strives to be as unambiguous as possible,
101 #' without compromising on readability.
102 #' In a list, to distinguish between vectors and nested lists,
103 #' the latter are surrounded by `[]` brackets.
104 #' Empty lists are shown as `[]`.
105 #' Vectors inside lists, of length not equal to one,
106 #' are surrounded by `<>` angle brackets.
107 #' Empty vectors are shown as `<>`.
108 #'
109 #' @return A character vector of the same length as `x`.
110 #' @inheritParams rlang::args_dots_used
111 #' @param x A vector.
112 #' @export
113 #' @examples
114 #' format_glimpse(1:3)
115 #'
116 #' # Lists use [], vectors inside lists use <>
117 #' format_glimpse(list(1:3))
118 #' format_glimpse(list(1, 2:3))
119 #' format_glimpse(list(list(1), list(2:3)))
120 #' format_glimpse(list(as.list(1), as.list(2:3)))
121 #' format_glimpse(list(character()))
122 #' format_glimpse(list(NULL))
123 #'
124 #' # Character strings are always quoted
125 #' writeLines(format_glimpse(letters[1:3]))
126 #' writeLines(format_glimpse(c("A", "B, C")))
127 #'
128 #' # Factors are quoted only when needed
129 #' writeLines(format_glimpse(factor(letters[1:3])))
130 #' writeLines(format_glimpse(factor(c("A", "B, C"))))
131 format_glimpse <- function(x, ...) {
132 check_dots_used()
133 UseMethod("format_glimpse")
134 }
135
136 # A variant with collapse and without checks, for format_glimpse.list()
137 format_glimpse_1 <- function(x, ..., .inner = NULL) {
138 if (!is_null(.inner) && .inner) {
139 collapse(format_glimpse_(x, ..., .inner = .inner))
140 } else {
141 paste0(format_glimpse_(x, ...), collapse = crayon_grey_0.6(", "))
142 }
143 }
144
145 format_glimpse_ <- function(x, ...) {
146 UseMethod("format_glimpse")
147 }
148
149
150 #' @export
151 format_glimpse.default <- function(x, ...) {
152 dims <- dim(x)
153
154 if (is.null(dims)) {
155 out <- format(x, trim = TRUE, justify = "none")
156 style_na_if(out, if (is.atomic(x)) is.na(x) else FALSE)
157 } else {
158 dims_out <- paste0(dims, collapse = " x ")
159 paste0("<", class(x)[[1]], "[", dims_out, "]>")
160 }
161 }
162
163 #' @export
164 format_glimpse.list <- function(x, ..., .inner = FALSE) {
165 if (!.inner && length(x) == 0) {
166 return("list()")
167 }
168
169 out <- map_chr(x, format_glimpse_1, .inner = TRUE)
170 # Surround vectors by <>
171 # Only surround inner lists by []
172 list <- map_lgl(x, is.list)
173 scalar <- rep_along(x, TRUE)
174 scalar[!list] <- (map_int(x[!list], length) == 1L)
175 out[!scalar] <- paste0("<", out[!scalar], ">")
176 out[list] <- paste0("[", out[list], "]")
177
178 out
179 }
180
181 #' @export
182 format_glimpse.character <- function(x, ...) {
183 out <- encodeString(as.character(x), quote = '"')
184 style_na_if(out, is.na(x))
185 }
186
187 #' @export
188 format_glimpse.factor <- function(x, ...) {
189 if (any(grepl(",", levels(x), fixed = TRUE))) {
190 out <- encodeString(as.character(x), quote = '"')
191 } else {
192 out <- format(x, trim = TRUE, justify = "none")
193 }
194 style_na_if(out, is.na(x))
195 }