Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Produce a string that summarizes a vector of integers by replacing sequential values with the start and end value of the sequence

Tags:

r

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"
like image 892
digitalmaps Avatar asked Feb 08 '12 03:02

digitalmaps


1 Answers

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=", ")
like image 50
Vincent Zoonekynd Avatar answered Nov 12 '22 09:11

Vincent Zoonekynd