0

I have a variable that should be numeric but is a character, this variable has two types of numeric values, when I convert them to numeric one is not recognized as a number:

num <-c("3,98E+03", "3,98E+03","0.003382932", "5,22E+02", "0.005464587")
as.numeric(num)
NAs introduced by coercion[1]          NA          NA 0.003382932          NA 0.005464587

I don't want to have NA introduced. Thank you!

2 Answers2

1

You can replace the , with . using sub:

as.numeric(sub(",", ".", num, fixed = TRUE))
#[1] 3.980000e+03 3.980000e+03 3.382932e-03 5.220000e+02 5.464587e-03
GKi
  • 37,245
  • 2
  • 26
  • 48
1

The readr package has helpful functions to parse numbers from a string which may be more generalisable. string_replace() also replaces the , with a . similar to answer by @GKi

library(stringr)
library(readr)

parse_number(str_replace(num, ",", "."))