# Ignoring text when converting strings of text to numbers

I have a string of measurements--mostly numbers, but occasionally an NA. Right now Mathematica is reading it all as text, so I'm using

Read[StringToStream[#], Number] & /@ z;


to convert to a number string, where z is the string.

Is there a way to skip the NA whenever it appears?

Edit: the numbers are all in scientific notation (2.00E-07)

Sample string:

{NA,NA,NA,2.05E-08,2.07E-06,3.45E-09,7.52E-07,NA,NA...}

• Can you post a sample string? Commented Jan 23, 2019 at 20:08
• Why not just remove the NA afterwards, DeleteCases[z, NA]? Commented Jan 23, 2019 at 20:35
• You sample string is not a string. Please put some effort in that :)
– Kuba
Commented Jan 24, 2019 at 7:11

Using the three-argument form of Interpreter to provide a default value (here, Indeterminate) in case of failure:

int = Interpreter["Number", Not@*FailureQ, Indeterminate &];

s = "{NA,NA,NA,2.05E-08,2.07E-06,3.45E-09,7.52E-07,NA,NA}";
int /@ StringSplit[s, {"{", "}", ","}]

(*    {Indeterminate, Indeterminate, Indeterminate, 2.05*10^-8,
2.07*10^-6, 3.45*10^-9, 7.52*10^-7, Indeterminate,
Indeterminate}                                              *)


Any default value can be picked, for example Nothing:

int2 = Interpreter["Number", Not@*FailureQ, Nothing &];
int2 /@ StringSplit[s, {"{", "}", ","}]
(*    {2.05*10^-8, 2.07*10^-6, 3.45*10^-9, 7.52*10^-7}    *)


See also this question for an attempt to set up an Interpreter for the entire string, but failing due to a possible bug.

Let's assume this is your z:

z = List["NA", "NA", "NA", "2.05E-08", "2.07E-06", "3.45E-09", "7.52E-07", "NA", "NA"]


You could remove the "NA" before interpreting the numbers:

zClean = DeleteCases[z, "NA"]


A simpler string-to-number mechanism might be Interpreter:

Interpreter["Number"] /@ zClean


It might be better to clean the data afterward, however, because there may be other failure modes:

DeleteCases[Interpreter["Number"] /@ z, _Failure]


As much as I understood you, initially you have a list of strings, rather than a list of numbers. If this is right, try this:

str = {"NA", "NA", "NA", "2.05E-08", "2.07E-06", "3.45E-09",
"7.52E-07", "NA", "NA"}

Map[ToExpression[StringJoin[#]] &,
Map[Characters, str /. "NA" -> Nothing] /. "E" -> "*10^"]

(* {2.05*10^-8, 2.07*10^-6, 3.45*10^-9, 7.52*10^-7} *)


Let us check

Head /@ lst

(*  {Real, Real, Real, Real}   *)


Thus, now you have a list of numbers and can operate them in Mma.

Have fun!