datapasta icon indicating copy to clipboard operation
datapasta copied to clipboard

display of consecutive integers

Open ggrothendieck opened this issue 2 years ago • 1 comments

dpasta should represent consecutive integers compactly as dput does. Below dput is showing 1:3 but dpasta shows 1L, 2L, 3L. (This may be related to ALTREP. See [1] and [2]. )

bb <- data.frame(x = c(1L, 2L, 3L))

dpasta(bb)
## data.frame(
##            x = c(1L, 2L, 3L)
## )

dput(bb)
## structure(list(x = 1:3), class = "data.frame", row.names = c(NA, 
## -3L))

or maybe something like this is enough

make_shorter <- function(x) {
  stopifnot(is.integer(x))
  n <- length(x)
  if (n > 2L && identical(x, seq(x[1], x[n]))) paste0(x[1], ":", x[n])
  else if (n > 0L) toString(paste0(x, "L"))
  else "integer(0)"
}

# test
x1 <- c(2L, 3L, 4L)
x2 <- c(2L, 1L, 3L)

make_shorter(x1)
## [1] "2:4"
make_shorter(rev(x1))
## [1] "4:2"
make_shorter(x2)
## [1] "2L, 1L, 3L"
make_shorter(integer(0))
## "integer(0)"

ggrothendieck avatar Mar 05 '22 14:03 ggrothendieck

I learned something here - I was a little surprised that dput() returned the condensed expression, but looking at the source it's clear that it just uses deparse() (well, deparse1() since it's producing a string).

Running that over the results would be easy (deparse() is a more sophisticated and flexible function vs your make_shorter() but produces the same results on those test cases) and non-impactful (results should be identical either way) but I wonder how often such a use-case would come up that it's important (and not more confusing) to have this?

# test
x1 <- c(2L, 3L, 4L)
x2 <- c(2L, 1L, 3L)

deparse(x1)
## [1] "2:4"
deparse(rev(x1))
## [1] "4:2"
deparse(x2)
## [1] "c(2L, 1L, 3L)"
deparse(integer(0))
## "integer(0)"

bb <- data.frame(x = c(1L, 2L, 3L))
deparse1(bb)
[1] "structure(list(x = 1:3), class = \"data.frame\", row.names = c(NA, -3L))"

jonocarroll avatar Mar 07 '22 10:03 jonocarroll