Re: [R] Converting character strings to numeric

From: Petr Pikal <petr.pikal_at_precheza.cz>
Date: Fri 19 May 2006 - 17:11:10 EST


Hi

Maybe change your R version?

Works for me R 2.3.0pat, W 2000

> x1 <- "1159 1129 1124 -5 -0.44 -1.52"
> x2 <- c("1159","1129","1124","-5","-0.44","-1.52")
> x3 <- unlist(strsplit(x1," "))
> str(x2)
 chr [1:6] "1159" "1129" "1124" "-5" "-0.44" "-1.52"
> str(x3)

 chr [1:6] "1159" "1129" "1124" "-5" "-0.44" "-1.52"
> as.numeric(x2)

[1] 1159.00 1129.00 1124.00 -5.00 -0.44 -1.52
> as.numeric(x3)

[1] 1159.00 1129.00 1124.00 -5.00 -0.44 -1.52
>
>

HTH
Petr

On 19 May 2006 at 11:47, Mulholland, Tom wrote:

Date sent:      	Fri, 19 May 2006 11:47:54 +0800
From:           	"Mulholland, Tom" <Tom.Mulholland@dpi.wa.gov.au>
To:             	"R-Help (E-mail)" <r-help@stat.math.ethz.ch>
Subject:        	[R] Converting character strings to numeric

> I assume that I have missed something fundamental and that it is there
> in front of me in "An Introduction to R", but I need someone to point
> me in the right direction.
>
> > x1 <- "1159 1129 1124 -5 -0.44 -1.52"
> > x2 <- c("1159","1129","1124","-5","-0.44","-1.52")
> > x3 <- unlist(strsplit(x1," "))
> >
> >
> > str(x2)
> chr [1:6] "1159" "1129" "1124" "-5" "-0.44" "-1.52"
> > str(x3)
> chr [1:6] "1159" "1129" "1124" "-5" "-0.44" "-1.52"
> >
> > as.numeric(x2)
> [1] 1159.00 1129.00 1124.00 -5.00 -0.44 -1.52
> > as.numeric(x3)
> [1] 1159 1129 1124 NA NA NA
> Warning message:
> NAs introduced by coercion
>
> What do I have to do to get x3 to be the same as x2.
>
> Tom
>
> ______________________________________________
> 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

Petr Pikal
petr.pikal@precheza.cz



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 Received on Fri May 19 17:14:35 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 Fri 19 May 2006 - 18:10:12 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.