Wilcar
Wilcar

Reputation: 2513

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  

Upvotes: 2

Views: 135

Answers (3)

akrun
akrun

Reputation: 887118

Using str_replace

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

Upvotes: 2

PKumar
PKumar

Reputation: 11128

You can try this:

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

Upvotes: 1

Peter
Peter

Reputation: 12699

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")

Upvotes: 1

Related Questions