1
$\begingroup$

I have a sequence, from which I would like to select a subsequence, each term of the original sequence being included in the subsequence with probability $p$, independently of the other terms. That is, for each term in the sequence, I toss a biased coin to decide whether or not to keep it.

My question is whether there is a more elegant or more efficient way to do it, than this ?

list = {a, b, b, c, d, e, e, e, f, g};
p = 1/3;
Map[Part[list, #] &, Flatten[Position[RandomVariate[BernoulliDistribution[p], Length[list]], 1]]]

A typical output is:

{b, e, e}
$\endgroup$

1 Answer 1

1
$\begingroup$
p = 1/3;

SeedRandom[1]
Pick[list, RandomVariate[BernoulliDistribution[p], Length[list]], 1]
{a, b, g}
SeedRandom[1]
Extract[list, Position[1]@RandomVariate[BernoulliDistribution[p], Length[list]]]
{a, b, g}
SeedRandom[1]
list[[Flatten@Position[1]@RandomVariate[BernoulliDistribution[p], Length[list]]]]
 {a, b, g}
SeedRandom[1]
list[[PositionIndex[RandomVariate[BernoulliDistribution[p], Length[list]]]@1]]
{a, b, g}
$\endgroup$
2
  • 1
    $\begingroup$ Thank you so much ! What a lot of nice solutions from which to choose ! I will use your first one :) $\endgroup$
    – Simon
    Commented Aug 3, 2020 at 23:18
  • 1
    $\begingroup$ A bit shorter: Pick[list, RandomChoice[{2/3, 1/3} -> {0, 1}, Length@list], 1]. $\endgroup$
    – Alan
    Commented Aug 4, 2020 at 0:55

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.