Skip to content

convert delimited strings with ranges to numeric

7 messages · Chris Stubben, Marc Schwartz, arun +2 more

#
Is there an easy way to convert character strings with comma-separated 
numbers and ranges to a numeric vector?

x<-  "2,5-7,10,12-15"

[1]  2  5  6  7 10 12 13 14 15

Thanks,
Chris
#
On Aug 14, 2013, at 12:41 PM, Chris Stubben <stubben at lanl.gov> wrote:

            
There is a general admonishment to not use the idiom eval(parse(text = ...)) which has become a 'fortune', however in this case:

x <-  "2,5-7,10,12-15"
[1]  2  5  6  7 10 12 13 14 15


The result of the inner use of gsub() is:
[1] "2,5:7,10,12:15"


which converts the '-' to ':', which can then be parsed as a sequence operator. The paste() creates:
[1] "c( 2,5:7,10,12:15 )"


which can then be evaluated as a single vector.


Regards,

Marc Schwartz
#
Hi,
May be this helps:
library(gsubfn)
as.numeric(strsplit(gsub("[c() ]","",gsubfn("([0-9]+)-([0-9]+)", ~as.numeric(seq(x,y)),x)),",")[[1]])
#[1]? 2? 5? 6? 7 10 12 13 14 15
A.K.



----- Original Message -----
From: Chris Stubben <stubben at lanl.gov>
To: r-help at r-project.org
Cc: 
Sent: Wednesday, August 14, 2013 1:41 PM
Subject: [R] convert delimited strings with ranges to numeric

Is there an easy way to convert character strings with comma-separated 
numbers and ranges to a numeric vector?

x<-? "2,5-7,10,12-15"

[1]? 2? 5? 6? 7 10 12 13 14 15

Thanks,
Chris
#
Neither gsubfn nor eval(parse)) is required, of course:
last <- x[length(x)]    ## alternately could use if() on the length of x
  seq(from=x[1],to=last)
  }))

[1]  2  5  6  7 10 12 13 14 15


Cheers,
 Bert
On Wed, Aug 14, 2013 at 3:34 PM, arun <smartpink111 at yahoo.com> wrote:

  
    
#
I had earlier came up with a similar kind of function, though didn't posted.

unlist(lapply(strsplit(x,",")[[1]],function(x) sapply(strsplit(x,"-"),function(x) {x1<-as.numeric(x);if(length(x1)==2) seq(x1[1],x1[2]) else x1})))

A.K.

----- Original Message -----
From: Bert Gunter <gunter.berton at gene.com>
To: arun <smartpink111 at yahoo.com>
Cc: Chris Stubben <stubben at lanl.gov>; R help <r-help at r-project.org>; Marc Schwartz <marc_schwartz at me.com>
Sent: Wednesday, August 14, 2013 8:10 PM
Subject: Re: [R] convert delimited strings with ranges to numeric

Neither gsubfn nor eval(parse)) is required, of course:
? last <- x[length(x)]? ? ## alternately could use if() on the length of x
? seq(from=x[1],to=last)
? }))

[1]? 2? 5? 6? 7 10 12 13 14 15


Cheers,
Bert
On Wed, Aug 14, 2013 at 3:34 PM, arun <smartpink111 at yahoo.com> wrote:

  
    
#
Better yet!

-- Bert
On Wed, Aug 14, 2013 at 6:03 PM, Richard M. Heiberger <rmh at temple.edu> wrote: