# Summing up elements of nested lists based on conditions from another list

Here is a simplified version of my question, nothing that I have a much larger dataset.

I have a list of samples of proportions:

samples = {{0.1, 0.5, 0.4}, {0.3, 0.3, 0.4}, {0.3, 0.6, 0.1}}


and a mapping that corresponds to what each element of each sample refers to (assume they are years):

mapping = {1999, 2000, 2001}


I want to return the share of observations for each sample that are greater than 2000. I am trying to use MapThread. I can do each sample separately:

Total[MapThread[If[#1 > 2000, 0, #2] &, {mapping, samples[[1]]}]]
Total[MapThread[If[#1 > 2000, 0, #2] &, {mapping, samples[[2]]}]]
Total[MapThread[If[#1 > 2000, 0, #2] &, {mapping, samples[[3]]}]]


0.6

0.6

0.9

Is there a way to return this in one line, and in one list like:

{0.6, 0.6, 0.9}

• If you use Thread[{mapping, Transpose[samples]}] you get {{1999, {0.1, 0.3, 0.3}}, {2000, {0.5, 0.3, 0.6}}, {2001, {0.4, 0.4, 0.1}}} and could use Select to pick out those years greater than 2000. You can then transpose back if you want. – Mark R Jun 17 '19 at 6:03
• Please provide the data for states and make sure your code runs. – Roman Jun 17 '19 at 6:09

You can create a function that can be Mapped to samples:

f = Total[MapThread[If[#1 > 2000, 0, #2] &, {mapping, #}]] &
f /@ samples


{0.6, 0.6, 0.9}

samples.UnitStep[2000 - mapping]


{0.6, 0.6, 0.9}

mask = Boole[# <= 2000] & /@ mapping;
(* or  mask = UnitStep[2000 - mapping] *)
Total[Pick[samples, mask & /@ samples, 1], {2}]
(* alternatively, Total[Pick[#, mask, 1]] & /@ samples *)


{0.6, 0.6, 0.9}

assoc = AssociationThread[mapping -> #] & /@ samples
Total@*KeySelect[# <= 2000 &] /@ assoc


{0.6, 0.6, 0.9}