简体   繁体   中英

Can't convert character to numeric in R

I'm trying to convert values from character to numeric, but R introduces NAs. I have examined one of the problematic values:

> x
[1] "11 914 711.5"
> length(x)
[1] 1
> typeof(x)
[1] "character"
> as.numeric(x)
[1] NA
Warning message:
NAs introduced by coercion 

Does anybody have any idea how to fix this?

You could first split your string and then convert them to numeric:

as.numeric(unlist(strsplit(x, ' ')))
[1]  11.0 914.0 711.5

It's not clear what you want. The previous answers and comments assumes you have several numbers in 'x'. Another interpretation gives this solution:

as.numeric(gsub(" ","",x))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM