Suppose I have a list like:


I could use a Map to calculate over each row the "amount" * "price" easily like

Map[#[[2]] #[[3]] &, data[[2 ;;]]]

But I would prefer to write something like

Map["amount" "price"&, data[[2;;]]]

This would be convenient because sometimes the columns are shifted in another order. I tried to work with Rules but the evaluation order is a problem. Is there a way to do this? When I use

r = Thread[Rule[{"product", "amount", "price"}, Range@3]]

I could use

Map[(#[["amount"]] #[["price"]] /. r) &, data[[2 ;;]]]

It works with a complaint about the part specification

Map[(#[["amount"/.r]] #[["price"/.r]]) &, data[[2 ;;]]]

works but is not much better then hard coded numbers.

Any thoughts?

  • $\begingroup$ new = AssociationThread[First@data -> #] & /@ Rest[data]; new[[All, {"product", "price"}]] // Values? $\endgroup$ – Kuba Jan 10 at 13:15
  • $\begingroup$ @Kuba thx but that doesn't do the multiplication of amount and price right? $\endgroup$ – Lou Jan 10 at 13:19
  • $\begingroup$ You can do whatever query you want once you have a list of associations. $\endgroup$ – Kuba Jan 10 at 13:58
assoc = AssociationThread[data[[1]] -> #] & /@ data[[2 ;;]];
Map[#amount #price &]@assoc

{100, 300, 1000}

  • $\begingroup$ o wow I completely forgot about the slotnames stuff. Great! $\endgroup$ – Lou Jan 10 at 13:22

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.