简体   繁体   中英

Convert characters to numeric

How can I convert characters to numeric values?

 x <-c("0", "0,10", "18,20", "1,00")

I tried

 x <- as.numeric(x)

Without success

Output expected a numeric vector:

0  
0.1  
18.2  
1  

Try:

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

- output

str(as.numeric(sub(",", ".", x)))
#>  num [1:4] 0 0.1 18.2 1

data

x <-c("0", "0,10", "18,20", "1,00")

You can try this:

type.convert(c("0", "0,10", "18,20", "1,00"), as.is=TRUE, dec=',')

Using str_replace

library(stringr)
as.numeric(str_replace(x, ",", "."))
#[1]  0.0  0.1 18.2  1.0

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