I am looking for an efficient way to simplify a vector of integers as a summary string, in order to format it to fit in a table cell.
For example:
c(1, 2, 3, 4, 6, 8, 9, 10)
should produce
"1-4, 6, 8-10"
This becomes especially useful in cases where printing all elements in the vector would quickly make the table unreadable.
e.g.
c(1:50, 53, 89:120)
should produce
"1-50, 53, 89-120"
You want to group the elements into blocks of consecutive integers.
diff
can tell you if two consecutive elements are in the same block,
cumsum
can number the blocks
and tapply
can extract the first and last element of each block.
x <- c(1:50, 53, 89:120)
y <- tapply( x, c(0,cumsum(diff(x) != 1)), range )
# Format the result
y <- sapply(y, function(u)
if(u[1]==u[2]) u[1]
else paste(u,collapse=":")
)
paste(y, collapse=", ")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With