Mike Major
Mike Major

Reputation: 15

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};

Upvotes: 0

Views: 48

Answers (2)

agentp
agentp

Reputation: 6989

another way..

ReplacePart[data2, Position[data1, 0] -> 0]

{0, 2, 3, 0, 0}

note your example output doesn't agree with the text of your question.

Upvotes: 0

Chris Degnen
Chris Degnen

Reputation: 8645

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}

Upvotes: 1

Related Questions