[R] Converting character strings to numeric

Dimitrios Rizopoulos Dimitris.Rizopoulos at med.kuleuven.be
Fri May 19 07:16:19 CEST 2006


your code works for me, e.g.,

> x1 <- "1159 1129 1124 -5 -0.44 -1.52"
> x2 <- c("1159", "1129", "1124", "-5", "-0.44", "-1.52")
> x3 <- unlist(strsplit(x1, " "))
> ################
> all.equal(x2, x3)
[1] TRUE
> 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


maybe you could restart R and try again.

Best,
Dimitris

-- 
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven

Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/(0)16/336899
Fax: +32/(0)16/337015
Web: http://med.kuleuven.be/biostat/
     http://www.student.kuleuven.be/~m0390867/dimitris.htm


Quoting "Mulholland, Tom" <Tom.Mulholland at dpi.wa.gov.au>:

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


Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm




More information about the R-help mailing list