1
$\begingroup$

Assume that I have a list

a = {1,2,3,4,5,6};

and I want to have a function that outputs a subset of the list such that with probability p=0.2 each element will be selected i.e. we toss a coin (that is not fair because p=0.2) when going trough the list and if it's heads we will take that element to the new list. At this moment I have implemented this as

z={};
Do[If[RandomChoice[{0.2, 1 - 0.2} -> {True, False}], 
AppendTo[z, a[[i]]]], {i, 1, Length[a]}]

which seems a bit stupid way of doing it. Also I couldn't find a command in the documentation that does this.

$\endgroup$
2
  • 2
    $\begingroup$ a = {1, 2, 3, 4, 5, 6}; rv = RandomVariate[BernoulliDistribution[.2], Length@a]; Pick[a, rv, 1]? $\endgroup$
    – kglr
    Oct 4, 2018 at 12:36
  • 2
    $\begingroup$ Or Pick[ a, RandomChoice[{0.8, 0.2} -> {0, 1}, Length[a]], 1 ]. $\endgroup$ Oct 4, 2018 at 12:38

1 Answer 1

0
$\begingroup$
SeedRandom[123]
Pick[a, RandomVariate[BernoulliDistribution[.2], Length@a], 1]

{2, 3, 4}

Alternatively,

Flatten[RandomChoice[{.2, .8} -> {#, {}}] & /@ a]

{1, 5}

$\endgroup$
1
  • 1
    $\begingroup$ Also: Reap[Scan[If[RandomChoice[{.2, 1 - .2} -> {True, False}], Sow[#]] &, {1, 2, 3, 4, 5, 6}]] $\endgroup$ Oct 4, 2018 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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