3
$\begingroup$

I have a table with 10 columns. The last column contains a string; e.g.,

"center", "passageway 1", up to "passageway 8".

I want to change the last column so that the string is replaced with an assigned number, e.g,

"center" -> 0
"passageway 4" -> 4

I have added an image of the list. How I can change column J to numeric values as described above?

Thanks.


enter image description here

$\endgroup$

3 Answers 3

2
$\begingroup$
labels = Flatten@{"center", 
   Table["passageway " <> ToString[i], {i, 1, 8}]}
rules = MapThread[Rule, {labels, Range[0, Length@labels - 1]}]
{"center" -> 0, "passageway 1" -> 1, "passageway 2" -> 2, 
 "passageway 3" -> 3, "passageway 4" -> 4, "passageway 5" -> 5, 
 "passageway 6" -> 6, "passageway 7" -> 7, "passageway 8" -> 8}

You can create these rules manually if programming them in is difficult due to a lack of a pattern.


Creating mock data template (fewer columns):

alist := {TimeObject[
   {RandomInteger[{1, 12}], RandomInteger[{0, 59}], 
    RandomInteger[{0, 59}]}
   ]
  , RandomInteger[{-1, -200}]
  , RandomInteger[{-10, 10}]
  , RandomChoice[labels]
  }

Test:

(blist = Table[alist, {10}]) // Grid
blist /. rules // Grid

enter image description here

$\endgroup$
3
$\begingroup$
{"center", "passageway 7", "passageway 13"} /.
  {"center" -> 0,
   s_String?(StringStartsQ["passageway "]) :> ToExpression[StringDrop[s, 11]]}

(*    {0, 7, 13}    *)
$\endgroup$
2
$\begingroup$
list =
  {{10, "a", "cn"},
   {20, "b", "cn"},
   {30, "c", "pw 1"},
   {40, "d", "pw 1"},
   {50, "e", "pw 3"},
   {60, "e", "pw 3"},
   {70, "f", "pw 8"}};

Cases[{a__, b_} :> {a, ToExpression @ StringTake[b, -1]}] @
  ReplaceAll[{a__, "cn"} :> {a, "cn 0"}] @ list // TableForm

enter image description here

$\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.