Partial subtraction of two multi-dimensional lists

I have two multi-dimensional lists, for example:

ff = {{{3, 2}, {4, 2}, {8, 6}}}
ff2 = {{{3, 7}, {4, 1}, {8, 4}}}

I would like to subtract them but only in the second element, I want to obtain

ff2 - ff = {{{3, 5}, {4, -1}, {8, -2}}}

but I obtain

f2 - ff = {{{0, 5}, {0, -1}, {0, -2}}}

How can I achieve this?

• If the first elements of each pair are not equal, what should happen? Or will that never happen? Oct 21, 2023 at 21:38
• It will never happen Oct 21, 2023 at 21:50
• MapThread[#1 - #2*{0, 1} &, {ff, ff2}, 2]?
– ydd
Oct 21, 2023 at 21:57
• @ydd thank you. It seems to work. What does the last 2 stand for? Oct 21, 2023 at 22:00
• It specifies the Level of ff and ff2 to which #1 - #2*{0, 1} & is applied
– ydd
Oct 21, 2023 at 22:02

{{{3, 5}, {4, -1}, {8, -2}}}
ff = {{{3, 2}, {4, 2}, {8, 6}}};
ff2 = {{{3, 7}, {4, 1}, {8, 4}}};

1.

res =
Transpose[{ff2[[1]], ff[[1]]}] /. {{x_, a_}, {_, b_}} :> {x, a - b}

{{3, 5}, {4, -1}, {8, -2}}

2.

res =
KeyValueMap[List] @
GroupBy[Flatten[{ff, ff2}, 2], First -> Last, First @* Differences]

{{3, 5}, {4, -1}, {8, -2}}

3.

res =
KeyValueMap[List] @
Merge[First @* Differences] @ MapApply[Rule] @ Flatten[{ff, ff2}, 2]

{{3, 5}, {4, -1}, {8, -2}}

If you want the outermost brackets:

List @ res

{{{3, 5}, {4, -1}, {8, -2}}}

Clear[subtract];
subtract[x_, y_] := If[x == y, x, x - y];
SetAttributes[subtract, Listable]
subtract[ff2, ff]

{{{3, 5}, {4, -1}, {8, -2}}}

• Clear[subtract]; subtract = Function[{x, y}, If[x == y, x, x - y], Listable]; subtract[ff2, ff] Oct 22, 2023 at 2:34
ff3 = ff;
ff3[[All, All, 2]] //= ff2[[All, All, 2]] - # &;
ff3
{{{3, 5}, {4, -1}, {8, -2}}}
ReplacePart[ff, p : {_, _, 2} :> ff2[[## & @@ p]] - ff[[## & @@ p]]]
{{{3, 5}, {4, -1}, {8, -2}}}
ff2-ff.{{0,0},{0,1}}

(* {{{3,5},{4,-1},{8,-2}}} *)

Or

ff2 - Map[{0,Last@#}&, ff,{2}]

(* {{{3,5},{4,-1},{8,-2}}} *)