6
$\begingroup$

I have a list of text and need to replace an element based on the text that appears in the element before it. Example of my list:

list={{"yes","can","fgh"},{"yes","can",""},{"yes","not","fgh"},{"yes","can","srts"},
      {"yes","not","h"}}

I would like to replace all items in column 3 with "This" when column 2's entry is "can".

I have tried to do this using /. and If but without success. I think I need to use a rule but don't know the first thing about how to do this.

$\endgroup$

1 Answer 1

10
$\begingroup$

Try this:

Replace[list, {x_, "can", _} :> {x, "can", "This"}, 1]

OR

list /. {x_, "can", _} :> {x, "can", "This"}
{{"yes", "can", "This"}, {"yes", "can", "This"}, {"yes", "not", "fgh"},
 {"yes", "can", "This"}, {"yes", "not", "h"}}

As per your comment, use Alternatives (|):

Replace[list, {x_, y : "can" | "cann", _} :> {x, y, "This"}, 1]
$\endgroup$
9
  • $\begingroup$ Can you please walk me through what these symbols mean so I can use them in future? The first option you have given I read like this: $\endgroup$
    – lara
    Oct 13, 2014 at 2:04
  • 1
    $\begingroup$ @LaraJordan Sure. What I've done here is use rules with pattern matching. With Replace, Mathematica tries to match the first argument using rules provided in the second argument. In this case the first argument is your original list which containes a list of triples. So I matched those triples with the rule {x_, "can", _}. What this rule says is match any triple where the second column is "can", then using :> (RuleDelayed), I then replace the matched triples with {x, "can", "This"}, where I keep the first two columns the same but replace the third column with the desired "This" $\endgroup$
    – RunnyKine
    Oct 13, 2014 at 2:13
  • $\begingroup$ This is a good resource, if you're not familiar with Mathematica $\endgroup$
    – RunnyKine
    Oct 13, 2014 at 2:18
  • $\begingroup$ Thanks, that pretty much solves it but I have an addition to the question. What if instead of just replacing all items in column 3 with "This" when column 2's entry is "can", I also want to apply this rule when items in column 2 are any in a list {"can","cann",...}. I have tried using Table but this just gives me x sets of lists, each one with one rule applied. $\endgroup$
    – lara
    Oct 13, 2014 at 2:45
  • $\begingroup$ @LaraJordan See my update. $\endgroup$
    – RunnyKine
    Oct 13, 2014 at 2:51

Your Answer

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

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