2
$\begingroup$

Let's imagine I have the following table structure

data = {{a, b}, {c, d}, {e, f}};

and I want to transform it into the following table

dataEdited = {{a, (f[a] + f[b])/f[a]}, {c, (f[c] + f[d])/f[c]}, ...}

by leaving the first column unchanged and applying a function to the second column which also involves the first column.

My attempt is to apply MapAt to the second column, but I don't know how I can access the first column in this way. In the small example below I just apply the sine function to the second column.

data = {{a, b}, {c, d}, {e, f}};
dataEdited = Transpose[MapAt[Sin /@ #1 &, Transpose[data], 2]];

Any ideas or "best practice" recommendations how to handle this kind of operations?

$\endgroup$
  • 1
    $\begingroup$ data /. {a_, b_} :> {a, (f[a] + f[b])/f[a]} $\endgroup$ – alancalvitti Nov 2 '14 at 14:02
0
$\begingroup$

I like the solutions that @kguler present. Here is another solution (please tell me if there is a drawback with this):

data = {{a, b}, {c, d}, {e, f}};
dataEdited = data /. {a_, b_} -> {a, (f[a] + f[b])/f[a]}

{{a, (f[a] + f[b])/f[a]}, {c, (f[c] + f[d])/f[c]}, {e, (f[e] + f[f])/ f[e]}}

Edit: I see that @alancalvitti already showed this (but with :> instead of ->). Sorry, not my meaning to steal your answer.

$\endgroup$
  • $\begingroup$ thank you, very nice and easily readable code :-) is there any disadvantage to the examples given by kguler? $\endgroup$ – Mathias Nov 3 '14 at 21:01
1
$\begingroup$
data = {{a, b}, {c, d}, {e, f}};

ClearAll[foo, f1, f2, f3];
f1 = MapAt[Divide[Plus @@ foo /@ {##}, foo@#] & @@ # &,Transpose[{#[[All, 1]], #}], {{All, 2}}] &;
f2 = MapAt[Divide[Plus@##, #] &@@ # &, Transpose[{#[[All, 1]], Map[foo, #, {-1}]}], {{All, 2}}] &;
f3 = {#1, (foo[#] + foo[#2])/foo[#]} & @@@ # &;

f1 @ data == f2 @ data ==f3 @ data
(* True *)

f1 @ data

enter image description here

$\endgroup$
0
$\begingroup$
data = {{a, b}, {c, d}, {e, f}};
transform[{x_, y_}] := {x, (f[x] + f[y])/f[x]}

then

transform/@data

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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