[R] Compressing a sequence
Rui Barradas
ru|pb@rr@d@@ @end|ng |rom @@po@pt
Sat Feb 22 13:35:55 CET 2025
Às 00:46 de 22/02/2025, Dennis Fisher escreveu:
> R 4.4.0
> OS X
>
> Colleagues
>
> I have a sequence like:
> 1, 3, 4, 5, 7, 8, 12, 13, 14, 15, 20
>
> I would like to display it as:
> 1, 3-5, 7-8, 12-15, 20
>
> Any simple ways to accomplish this?
>
> Dennis
>
>
> Dennis Fisher MD
> P < (The "P Less Than" Company)
> Phone / Fax: 1-866-PLessThan (1-866-753-7784)
> www.PLessThan.com
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
Hello,
Here is a way with package R.utils, function seqToIntervals.
x <- scan(text = "1, 3, 4, 5, 7, 8, 12, 13, 14, 15, 20", sep = ",")
mat <- R.utils::seqToIntervals(x)
apply(mat, 1L, \(m) {
ifelse(m[1L] == m[2L], m[1L], paste(m, collapse = "-"))
})
#> [1] "1" "3-5" "7-8" "12-15" "20"
If you want to be fancy, define a special class that prints like that.
x <- scan(text = "1, 3, 4, 5, 7, 8, 12, 13, 14, 15, 20", sep = ",")
as_seqInterval <- function(x) {
old_class <- class(x)
class(x) <- c("seqInterval", old_class)
x
}
print.seqInterval <- function(x, ...) {
mat <- R.utils::seqToIntervals(x)
out <- apply(mat, 1L, \(m) {
ifelse(m[1L] == m[2L], m[1L], paste(m, collapse = "-"))
})
print(out)
}
y <- as_seqInterval(x)
class(y)
#> [1] "seqInterval" "numeric"
# autoprinting y
y
#> [1] "1" "3-5" "7-8" "12-15" "20"
# explicit printing y
print(y)
#> [1] "1" "3-5" "7-8" "12-15" "20"
Hope this helps,
Rui Barradas
--
Este e-mail foi analisado pelo software antivírus AVG para verificar a presença de vírus.
www.avg.com
More information about the R-help
mailing list