2
$\begingroup$

There is a string in this form:

<12> cfg <15.21>  bhg    v<(24)>    e<65>   True
<12> cfg <15.21>  bhg    v<33>      e<(77)> False
<83> fff <67>     bhg     < >       e<(43)> True
<11> fff <14.21>  bff    v<(1.42)>  e<44>   True
<76> cfg <76.3>   fff     < >       e<21>   True
<98> cff <34>     rrs    v<33>       < >    True

The point is the numbers in the parenthesis indicate negative numbers and there are as well some missing values. I need to refine this string in a form to get a vector of output in this form:

{{12,15.21,-24,65,T},{12,15.21,33,-77,F},{83,67,-43,-43,T},
{11,14.21,-1.42,44,T},{76,76.3,NA,21,T},{98,NA,33,NA,T}}

What I did is to apply this:

Partition[StringCases[list, NumberString],4]

But as some rows have different structure then it is not working. And also this is not able to capture the negative numbers, and even this is neglecting the last column!!

How is it possible to manage this?

$\endgroup$
0

2 Answers 2

5
$\begingroup$

Here is one approach.

StringReplace[string,
  {"< >" -> "NA", "(" -> "-", "e<" | "v<" | "<" | ">" | ")" -> " "}
]

ImportString[%, "Table"][[All, {1, 3, 5, 6, 7}]] /. {"True" -> True, "False" -> False}
{{12, 15.21, -24, 65, True}, {12, 15.21, 33, -77, False}, {83, 67, "NA", -43, True},
 {11, 14.21, -1.42, 44, True}, {76, 76.3, "NA", 21, True}, {98, 34, 33, "NA", True}}
$\endgroup$
2
  • $\begingroup$ This method is not robust as there are cases of < > which the blank is different in length, like < ' > $\endgroup$
    – Morry
    Commented Aug 2, 2013 at 22:04
  • $\begingroup$ @Morry You could use e.g. "<" ~~ Whitespace ~~ ">" -> "NA" to handle that, but if there are more of these issues why don't you upload larger, more representative data? I'd be happy to try to make my solution more general if I knew what it should expect. $\endgroup$
    – Mr.Wizard
    Commented Aug 3, 2013 at 0:16
2
$\begingroup$

One way using string patterns and StringCases like this:

string = ImportString["<12> cfg <15.21>  bhg    v<(24)>    e<65>   True
  <12> cfg <15.21>  bhg    v<33>      e<(77)> False
  <83> fff <67>     bhg     < >       e<(43)> True
  <11> fff <14.21>  bff    v<(1.42)>  e<44>   True
  <76> cfg <76.3>   fff     < >       e<21>   True
  <98> cff <34>     rrs    v<33>       < >    True", "Lines"];
StringCases[string, {
  "<" ~~ p : NumberString ~~ ">" :> ToExpression[p],
  "<(" ~~ n : NumberString ~~ ")>" :> -ToExpression[n],
  "<" ~~ Whitespace.. ~~ ">" -> "NA",
  b : "True" | "False" :> b /. {"True" -> "T", "False" -> "F"}
  }]
{{12, 15.21, -24, 65, "T"}, {12, 15.21, 33, -77, "F"}, {83, 67, 
  "NA", -43, "T"}, {11, 14.21, -1.42, 44, "T"}, {76, 76.3, "NA", 21, 
  "T"}, {98, 34, 33, "NA", "T"}}
$\endgroup$

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.