4
$\begingroup$

I have a list of strings representing different types of data

{{"gw12-26b-pl1", "63.6512", "0.0076", "--", "Al2O3", "%", "23.4002"},
 {"gw12-26b-pl3", "65.1182", "0.1257", "--", "SiO2", "ppm", "76.3388"}};

I want to convert the 'numerical strings' to expressions so that I can work with them. I want to end up with something like:

{{"gw12-26b-pl1", 63.6512, 0.0076, "--", "Al2O3", "%", 23.4002},
 {"gw12-26b-pl3", 65.1182, 0.1257, "--", "SiO2", "ppm", 76.3388}}

I tried to convert the whole list using ToExpression and then convert non-numeric elements back to strings but this doesn't work because it is trying to evaluate elements like gw12-26b-pl1as an expression.

Can anyone suggest an easy way to do this?

$\endgroup$

1 Answer 1

8
$\begingroup$

A way of doing the replacement not explicitly, but implicitly with a function is to define a function t, which converts a NumberString to the number and leaves the rest untouched. Giving t the attribute Listable and it can directly be applied on the list:

SetAttributes[t, {Listable}];
t[a_String /; StringMatchQ[a, NumberString]] := ToExpression[a];
t[a_] := a;

Now you have

t@{{"gw12-26b-pl1", "63.6512", "0.0076", "--", "Al2O3", "%", 
   "23.4002"}, {"gw12-26b-pl3", "65.1182", "0.1257", "--", "SiO2", 
   "ppm", "76.3388"}}
(* {{"gw12-26b-pl1", 63.6512, 0.0076, "--", "Al2O3", "%", 
  23.4002}, {"gw12-26b-pl3", 65.1182, 0.1257, "--", "SiO2", "ppm", 
  76.3388}} *)
$\endgroup$
12
  • $\begingroup$ Thanks! This solution is elegant because it works on nested lists. e.g. t@ {"67", "34d-45b", {"b", "27", {"ww", "11.1", {{"67.1"}, "aa", "3"}}}} $\endgroup$
    – geordie
    Commented May 20, 2014 at 1:50
  • 3
    $\begingroup$ To speed up the code, you can use Internal`StringToDouble instead of ToExpression $\endgroup$
    – Murta
    Commented May 20, 2014 at 1:52
  • 1
    $\begingroup$ @rasher I edited your answer and voted to undelete it. If you make your pattern restrict to strings, you don't get error messages when doing a ReplaceAll. $\endgroup$
    – halirutan
    Commented May 20, 2014 at 2:07
  • 1
    $\begingroup$ @MikeHoneychurch here $\endgroup$
    – Murta
    Commented May 20, 2014 at 3:30
  • 2
    $\begingroup$ @rasher It's the other way around, because I wrote my version as an addition to your answer. And yes, I can vote for undeletion no matter whether you deleted your answer. In the end I would respect your decision, but I hope you don't take the whole issue too hard that. It always happens, and especially me, that I give a solution which is specific to the OP's needs. Often the OP then decides that a more general version was required. That's SE live I guess. $\endgroup$
    – halirutan
    Commented May 20, 2014 at 8:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.