[R] Converting character strings to numeric

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri May 19 09:02:55 CEST 2006


On Fri, 19 May 2006, Mulholland, Tom wrote:

> After replies off the list which indicate the code should work. I tried a variety of approaches.
>
> Rebooting, Using the --vanilla option and then removing the whole lot and resinstalling. It now works.
>
> I guess it's another of those windows things?

No, it works under Windows.

What you have not shown us is x3:

> x3
[1] "1159"  "1129"  "1124"  "-5"    "-0.44" "-1.52"

My guess is that you have something invisible in x1, e.g. a nbspace not a 
space (although that does not fully explain the results).  What does

> charToRaw(x1)
  [1] 31 31 35 39 20 31 31 32 39 20 31 31 32 34 20 2d 35 20 2d 30 2e 34 34 20 2d
[26] 31 2e 35 32

give for you?



>
> Thanks to those that helped.
>
>> -----Original Message-----
>> From: r-help-bounces at stat.math.ethz.ch
>> [mailto:r-help-bounces at stat.math.ethz.ch]On Behalf Of Mulholland, Tom
>> Sent: Friday, 19 May 2006 11:48 AM
>> To: R-Help (E-mail)
>> 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

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list