R: Group number string to from-to form -


i have (after long script) value/vector like

258  814  815  816  817  818  819  862  863  864  865  866  867  868 869  870  871  872  1377 1378 1379 1393 1394 1395 1396 1397 1398 1399 1400 ........ 

this quite difficult controll over. if there way to

258 814-819 862-872 1377-1379 1393-1400 , on.... 

i have thought sort of loop adds value string if x[i+1]!=x[i]+1, can take time if dataset large...

for input

x <- c(258, 814:819, 862:872, 1377:1379, 1393:1400) 

the output should be

"258\n814-819\n862-872\n1377-1379\n1393-1400" 

adding on josh's answer should work:

rr <- rle(x - seq_along(x)) rr$values <- seq_along(rr$values) s <- split(x, inverse.rle(rr))  paste(lapply(s, fun = function(x) if(length(x) > 1){paste(x[1], x[length(x)], sep="-")}else{x}), collapse="\n")  [1] "258\n814-819\n862-872\n1377-1379\n1393-1400" 

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -