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 -- Chris Stubben Los Alamos National Lab Bioscience Division MS M888 Los Alamos, NM 87545
On Aug 14, 2013, at 12:41 PM, Chris Stubben <stubben at lanl.gov> wrote:> 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 >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"> eval(parse(text = paste("c(", gsub("\\-", ":", x), ")")))[1] 2 5 6 7 10 12 13 14 15 The result of the inner use of gsub() is:> gsub("\\-", ":", x)[1] "2,5:7,10,12:15" which converts the '-' to ':', which can then be parsed as a sequence operator. The paste() creates:> paste("c(", gsub("\\-", ":", x), ")")[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
--
Chris Stubben
Los Alamos National Lab
Bioscience Division
MS M888
Los Alamos, NM 87545
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.