[R] string-to-number
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Sat Aug 19 14:12:13 CEST 2006
"Charles Annis, P.E." <Charles.Annis at statisticalengineering.com> writes:
> 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?
3) you're almost there, just not realizing it:
> x <- "3,6,10"
> as.numeric(strsplit(x,split = ",")[[1]])
[1] 3 6 10
or for that matter
> scan(textConnection(x), sep=",")
Read 3 items
[1] 3 6 10
although that leaves you with a dangling open connection.
--
O__ ---- Peter Dalgaard Øster Farimagsgade 5, Entr.B
c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list