3
$\begingroup$

I have several lists that I would like to match and operate values among them. For simplicity assume I have these two lists:

l1 = Transpose[{Range[1980, 2010, 1], Range[31]}]
l2 = {{1990, 1,100}, {2000, 2,200}, {2010, 3,300}}

I would like to divide the third column of l2 by the second column in l1 matching the year in both lists.

I should obtain:

l3 = {{1990, 1, 100/11}, {2000, 2, 200/21}, {2010, 3, 300/31}}

How can I set a function to do that?

$\endgroup$
5
$\begingroup$

Lookup says it all... ;)

lookuptable = AssociationThread[l1[[All, 1]], l1[[All, 2]]];
l3 = l2;
l3[[All, 3]] /= Lookup[lookuptable, l2[[All, 1]]];
l3

{{1990, 1, 100/11}, {2000, 2, 200/21}, {2010, 3, 300/31}}

$\endgroup$
  • $\begingroup$ Thanks Henrik. Gracias Tocayo! worked fine. $\endgroup$ – Enrique Vargas Jun 7 '18 at 18:21
  • $\begingroup$ I'm always glad to be of help! You're welcome! $\endgroup$ – Henrik Schumacher Jun 7 '18 at 19:14
  • 2
    $\begingroup$ For brevity, likely at the cost of some performance, you can eliminate AssociationThread and use simply Lookup[Rule @@@ l1, l2[[All, 1]]] $\endgroup$ – Mr.Wizard Jun 8 '18 at 6:44
1
$\begingroup$
Cases[GatherBy[Join[l1, l2], First], {x_, y_} :> {x[[1]], y[[2]], y[[3]]/x[[2]]}]

{{1990, 1, 100/11}, {2000, 2, 200/21}, {2010, 3, 300/31}}

$\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.