Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

display of consecutive integers #131

Open
ggrothendieck opened this issue Mar 5, 2022 · 1 comment
Open

display of consecutive integers #131

ggrothendieck opened this issue Mar 5, 2022 · 1 comment

Comments

@ggrothendieck
Copy link

ggrothendieck commented Mar 5, 2022

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)"
@jonocarroll
Copy link
Contributor

jonocarroll commented Mar 7, 2022

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))"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants