Search code examples
stringreplacewolfram-mathematicalist-manipulation

Replacing elements of a list that depend on elements of other lists


I have two lists:

data1 = {0, 1, 1, 0, 0}

data2 = {1, 2, 3, 4, 5}

I want to replace the elements in data2 depending on the value of data1.

For example, if data1=0, i want data2 to replaced with 0, otherwise i want data2 to stay as it is.

The output i am looking for is:

data2 = {1, 0, 0, 4, 5};


Solution

  • For the required output, if data1 = 0, data2 is not replaced with 0.

    data1 = {0, 1, 1, 0, 0};
    data2 = {1, 2, 3, 4, 5};
    
    data2 = MapThread[If[#1 == 0, #2, 0] &, {data1, data2}]
    

    {1, 0, 0, 4, 5}

    also

    data2 = UnitStep[-Abs@data1]*data2
    

    {1, 0, 0, 4, 5}