Hi All,
Thanks in advance for your help. I'm trying to convert a string to an
integer vector. For instance, I will start with
a <- "1,2"
The result I want to end up with will be the equivalent of
c(1,2)
What's the best way to make the conversion? I've tried using
as.integer(a),
but R seems to balk at that.
Thanks,
Ben
--
View this message in context:
http://r.789695.n4.nabble.com/converting-a-string-to-an-integer-vector-tp4646610.html
Sent from the R help mailing list archive at Nabble.com.
Hello, Try this, It'll maybe help you: a <- "1,2" b <- strsplit(a,",") #split your data according to "," b <- unlist(b) # it creates a list, so we unlist the result to obtain a vector like c(1,2) -- View this message in context: http://r.789695.n4.nabble.com/converting-a-string-to-an-integer-vector-tp4646610p4646619.html Sent from the R help mailing list archive at Nabble.com.
Thank you very much. That appears to be what I wanted. -- View this message in context: http://r.789695.n4.nabble.com/converting-a-string-to-an-integer-vector-tp4646610p4646624.html Sent from the R help mailing list archive at Nabble.com.
Depending on what exactly you are trying to accomplish:> as.numeric(unlist(strsplit(a, ",")))[1] 1 2> read.csv(textConnection(a), header=FALSE)V1 V2 1 1 2 Sarah On Thu, Oct 18, 2012 at 9:08 AM, BenM <bmmoskow at amath.washington.edu> wrote:> Hi All, > Thanks in advance for your help. I'm trying to convert a string to an > integer vector. For instance, I will start with > > a <- "1,2" > > The result I want to end up with will be the equivalent of > > c(1,2) > > What's the best way to make the conversion? I've tried using as.integer(a), > but R seems to balk at that. > > Thanks, > > Ben-- Sarah Goslee http://www.functionaldiversity.org
Hi,
You can also try this:
a <- "1,2"
as.numeric(c(gsub("(.*)\\,(.*)","\\1",a),
gsub("(.*)\\,(.*)","\\2",a)))
#[1] 1 2
----- Original Message -----
From: BenM <bmmoskow at amath.washington.edu>
To: r-help at r-project.org
Cc:
Sent: Thursday, October 18, 2012 10:17 AM
Subject: Re: [R] converting a string to an integer vector
Thank you very much.? That appears to be what I wanted.
--
View this message in context:
http://r.789695.n4.nabble.com/converting-a-string-to-an-integer-vector-tp4646610p4646624.html
Sent from the R help mailing list archive at Nabble.com.
______________________________________________
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.