Re: [R] string-to-number

From: Roger Bivand <Roger.Bivand_at_nhh.no>
Date: Sat 19 Aug 2006 - 22:20:43 EST


On Sat, 19 Aug 2006, Charles Annis, P.E. wrote:

> 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.

repeated.measures.columns is a vector. Consider:

repeated.measures.columns <- c("3,6,10", "5,4,9") lst <- strsplit(repeated.measures.columns, split = ",") lapply(lst, as.numeric)

which is why 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]])

>
> 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.
>
> Charles.Annis@StatisticalEngineering.com
> phone: 561-352-9699
> eFax:  614-455-3265
> http://www.StatisticalEngineering.com
>  
>
> ______________________________________________
> R-help@stat.math.ethz.ch 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.
>

-- 
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Helleveien 30, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 95 43
e-mail: Roger.Bivand@nhh.no

______________________________________________
R-help@stat.math.ethz.ch 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.
Received on Sat Aug 19 22:28:42 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 - 00:20:26 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.