1
$\begingroup$

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}

$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – Mark R Jun 17 '19 at 6:03
  • $\begingroup$ Please provide the data for states and make sure your code runs. $\endgroup$ – Roman Jun 17 '19 at 6:09
3
$\begingroup$

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}

A few additional alternatives:

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}

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