Re: [R] string-to-number SUMMARY

From: Charles Annis, P.E. <>
Date: Sun 20 Aug 2006 - 00:08:49 EST

Much gratitude to Professor Ripley, Peter Dalgaard, Marc Schwartz, and Roger Bivand.

Roger Bivand wrote that ... strsplit() returns a list - one list component for each repeated.measures.columns element. Just pick off the one you want with
as.numeric(strsplit(repeated.measures.columns, split = ",")[[1]])

which had stumped me, since that syntax fails without the [[1]] specification.

Peter Dalgaard, who also suggested the [[1]] specification, pointed out that

scan(textConnection(x), sep=",")

will work, although that leaves you with a dangling open connection.

Marc Schwartz advised to ...
Use unlist() to take the output of strsplit() and convert it to a vector, before coercing to numeric.

as.numeric(unlist(strsplit(repeated.measures.columns, ",")))

Brian D. Ripley suggested that the following looks competitive, and is quite a bit more general (e.g. allows spaces, works with complex numbers)  

eval(parse(text=paste("c(", repeated.measures.columns, ")")))

and Marc Schwartz showed that Professor Ripley's suggestion is much faster than the competition with some system.time trials.

Many thanks to all.  

Charles Annis, P.E. phone: 561-352-9699
eFax: 614-455-3265  

-----Original Message-----
[] On Behalf Of Charles Annis, P.E. Sent: Saturday, August 19, 2006 7:59 AM
Subject: [R] string-to-number

Greetings, Amigos:

I have been trying without success to convert a character string,
> repeated.measures.columns

[1] "3,6,10"

into c(3,6,10) for subsequent use.

as.numeric(repeated.measures.columns) doesn't work (likely because of the commas)
[1] NA
Warning message:
NAs introduced by coercion

I've tried many things including
strsplit(repeated.measures.columns, split = ",")

which produces a list with only one element, viz: [[1]]
[1] "3" "6" "10"

as.numeric() doesn't like that either.

Clearly: 1) I cannot be the first person to attempt this, and 2) I've made this WAY harder than it is.

Would some kind soul please instruct me (and perhaps subsequent searchers) how to convert the elements of a string into numbers?

Thank you.

Charles Annis, P.E. phone: 561-352-9699
eFax:  614-455-3265 mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Sun Aug 20 03:33:21 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Sun 20 Aug 2006 - 06:21:15 EST.

Mailing list information is available at Please read the posting guide before posting to the list.