R - Create a string that sums the vector of integers, replacing consecutive values ​​with the initial and final value of the sequence

I am looking for an effective way to simplify a vector of integers as a summary string in order to format it in a table cell.

For instance:

c(1, 2, 3, 4, 6, 8, 9, 10) 

should produce

 "1-4, 6, 8-10" 

This becomes especially useful when printing all the elements in a vector quickly makes the table unreadable.

eg.

 c(1:50, 53, 89:120) 

should produce

 "1-50, 53, 89-120" 
+6
source share
1 answer

You want to group elements into blocks of consecutive integers. diff can tell you if two consecutive elements are in the same block, cumsum can indicate 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=", ") 
+9
source

Source: https://habr.com/ru/post/907903/


All Articles