Home > Enterprise >  How to parse scientific notation provided to r as a string?
How to parse scientific notation provided to r as a string?

Time:05-31

I have a variable in scientific notation that is been passed to my script as a string. as.numeric returns and NA when I try to convert it to numeric. However, if I provide the exact same number (without the quotes, of course) I can operate the variable normally. Is there a way to parse scientific notation that is provided as a character?

> varc = "4.38962*10^-8"
> as.numeric(varc)
[1] NA
Warning message:
NAs introduced by coercion 
> varn = 4.38962*10^-8 
> varn*10
[1] 4.38962e-07

CodePudding user response:

You could turn the 10^ into e using gsub, parse and evaluate.

eval(parse(text=gsub('\\*10\\^', 'e', "4.38962*10^-8")))
# [1] 4.38962e-08

Or as.numeric.

as.numeric(gsub('\\*10\\^', 'e', "4.38962*10^-8"))
# [1] 4.38962e-08
  •  Tags:  
  • r
  • Related