Skip to content

Commit

Permalink
Merge pull request #389 from anhqle/384-add-quote-for-factor-in-glimpse
Browse files Browse the repository at this point in the history
- `glimpse()` disambiguates outputs for factors if the levels contain commas (#384, @anhqle).
  • Loading branch information
krlmlr committed May 23, 2018
2 parents 8ad7706 + 74149a8 commit ebf5b97
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
11 changes: 9 additions & 2 deletions R/glimpse.R
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ glimpse.tbl <- function(x, width = NULL, ...) {
# every type needs at least three characters: "x, "
rows <- as.integer(width / 3)
df <- as.data.frame(head(x, rows))

cat_line("Variables: ", big_mark(ncol(df)))
if (ncol(df) == 0) return(invisible(x))

Expand All @@ -52,7 +51,6 @@ glimpse.tbl <- function(x, width = NULL, ...) {
var_names <- paste0("$ ", justify(ticked_names, right = FALSE), " ", var_types, " ")

data_width <- width - nchar(var_names) - 2

formatted <- map_chr(df, function(x) collapse(format_v(x)))
truncated <- str_trunc(formatted, data_width)

Expand Down Expand Up @@ -98,3 +96,12 @@ format_v.list <- function(x) {

#' @export
format_v.character <- function(x) encodeString(x, quote = '"')

#' @export
format_v.factor <- function(x) {
if (any(grepl(",", x, fixed = TRUE))) {
encodeString(as.character(x), quote = '"')
} else {
format(x, trim = TRUE, justify = "none")
}
}
10 changes: 10 additions & 0 deletions tests/testthat/test-glimpse.R
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ test_that("format_v for character", {
expect_equal(format_v(character()), character())
})

test_that("format_v for factor", {
expect_equal(format_v(factor(c("1", "a"))), c("1", "a"))
expect_equal(format_v(factor(c("foo", '"bar"'))), c("foo", "\"bar\""))
expect_equal(format_v(factor()), character())
# Add quotes around factor levels with comma
# so they don't appear as if they were two observations (GH 384)
expect_equal(format_v(factor(c("foo, bar", "foo", '"bar"'))),
paste0('"', c("foo, bar", "foo", "\\\"bar\\\""), '"'))
})

test_that("format_v for list", {
expect_equal(format_v(list(1:3)), "[<1, 2, 3>]")
expect_equal(format_v(as.list(1:3)), "[1, 2, 3]")
Expand Down

0 comments on commit ebf5b97

Please sign in to comment.