Debian Codegraph @

R/string_repr.R

raw
1 #' Short string representation for R objects
2 #'
3 #' This is inspired by the python function `repr` and produces a short
4 #' string representation of any \R object that is suitable for logging and error
5 #' messages. It is a generic so you can implement methods for custom S3 objects.
6 #'
7 #' @param x Any \R object.
8 #' @param width a scalar integer
9 #' @param ... passed on to methods
10 #'
11 #' @return a `scalar` character
12 #' @export
13 #'
14 #' @examples
15 #' string_repr(iris)
16 #' string_repr(LETTERS)
17 #' string_repr(LETTERS, 10)
18 string_repr <- function(
19 x,
20 width = 32,
21 ...
22 ){
23 assert(is_scalar_integerish(width))
24
25 if (width < 8){
26 warning("string_repr() does not support width < 8")
27 width <- 8L
28 }
29 UseMethod("string_repr")
30 }
31
32
33
34
35 #' @rdname string_repr
36 #' @export
37 string_repr.function <- function(
38 x,
39 width = 32L,
40 ...
41 ){
42 fmls <- names(formals(x))
43 len_fmls <- length(fmls)
44
45 if (len_fmls > 4){
46 fmls <- fmls[1:4]
47 fmls_fmt <- paste(fmls, collapse = ", ")
48 fmls_fmt <- paste0(fmls_fmt, ", +", len_fmls - length(fmls), "")
49 } else {
50 fmls_fmt <- paste(fmls, collapse = ", ")
51 }
52
53 fmt_class(paste(
54 fmt_class(class(x), open = "", close = ""), "(", fmls_fmt, ")",
55 sep = ""
56 ))
57 }
58
59
60 #' @rdname string_repr
61 #' @export
62 string_repr.data.frame <- function(
63 x,
64 width = 32L,
65 ...
66 ){
67 x_class <- fmt_class(class(x), open = "", close ="")
68 x_shape <- paste0(nrow(x),"x", ncol(x))
69
70 if (nchar(x_class) + nchar(x_shape) + 3L <= width){
71 res <- paste0("<", x_class, " ", x_shape, ">")
72 } else {
73 if (nchar(x_class) >= width - 2L){
74 x_class <- paste0(strtrim(x_class, width - 4L), "..")
75 }
76 res <- paste0("<", strtrim(x_class, width = width - 2L), ">")
77 }
78 res
79 }
80
81
82 #' @rdname string_repr
83 #' @export
84 string_repr.matrix <- string_repr.data.frame
85
86
87 #' @rdname string_repr
88 #' @export
89 string_repr.numeric <- function(
90 x,
91 width = 32L,
92 ...
93 ){
94 string_repr(format(x, justify = "none", drop0trailing = TRUE, trim = TRUE))
95 }
96
97
98 #' @rdname string_repr
99 #' @export
100 string_repr.default <- function(
101 x,
102 width = 32L,
103 ...
104 ){
105 if (is.recursive(x)){
106 x_class <- fmt_class(class(x), open = "", close ="")
107
108 if (nchar(x_class) >= width - 2L){
109 x_class <- paste0(strtrim(x_class, width - 4L), "..")
110 }
111 res <- paste0("<", strtrim(x_class, width = width - 2L), ">")
112
113 } else {
114 res <- ptrunc(x, collapse = ", ", width = width, dots = "..")
115
116 if (is_scalar(x)){
117 res <- paste0("`", res, "`")
118 } else {
119 res <- paste0("(", res, ")")
120 }
121 }
122
123 res
124 }