4
$\begingroup$

if I had a random list of numbers:

d = {1, 2, 3, 4, 5, 6}

Is it possible to use RandomSamplebut only sample list "d" given a probability "x." When you use RandomSample the probability of sampling is always guaranteed (i.e. you'll always have a sample as an output) but would it be possible so that RandomSample only works "x" percentage of time.

As an example if we take list "d", I want to perform RandomSample but the function only has a 30% chance of working. So 30% of the time, it'll sample from list "d" and then 70% of the time, I don't have any samples being obtained. Is there a simple way to perform this function?

$\endgroup$

3 Answers 3

4
$\begingroup$
fn = RandomChoice[{#3, 1 - #3} -> {RandomSample[#1, #2], {}}] &;

Use:

fn[list,number_of_samples,probability_of_sample_success]

Example:

fn[{1, 2, 3, 4, 5, 6}, 3, .3]

{2,1,5}

fn[{1, 2, 3, 4, 5, 6}, 3, .3]

{1,4,5}

fn[{1, 2, 3, 4, 5, 6}, 3, .3]

{}

$\endgroup$
2
  • $\begingroup$ @anton-antonov: Oops, looks like we had same basic idea, and you posted while I was typing. Happy to delete... $\endgroup$
    – ciao
    May 26, 2020 at 19:10
  • $\begingroup$ They are very similar, but different enough to keep both. (I think...) $\endgroup$ May 27, 2020 at 14:29
3
$\begingroup$

You can use RandomChoice to do weighted random choice of the sampling functions and use Through to apply those functions to your data.

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

SeedRandom[15]
Through[RandomChoice[{0.7, 0.3} -> {RandomSample[#, 1] &, Nothing &}, 12][d]]

(* {{3}, {5}, {1}, {6}, {1}, {4}, {4}, {3}, {3}} *)

SeedRandom[15]
Through[RandomChoice[{0.7, 0.3} -> {RandomSample[#, 1] &, None &}, 12][d]]

(* {None, None, {3}, {5}, {1}, {6}, {1}, {4}, {4}, None, {3}, {3}} *)
$\endgroup$
2
$\begingroup$

Perhaps this:

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

RandomChoice[
 Flatten@{70, ConstantArray[30/Length[d], Length[d]]} ->
  {{}, Sequence @@ d}
]

Let's check that it does what you want by drawing 10,000 samples:

RandomChoice[
  Flatten@{70, ConstantArray[30/Length[d], Length[d]]} ->
   {{}, Sequence @@ d},
  10000
] // Counts

(* Out: <|{} -> 6998, 3 -> 478, 2 -> 481, 1 -> 489, 5 -> 494, 4 -> 554, 6 -> 506|> *) 

The frequency of {} (i.e. the "no sample" response) is 6998/10000, i.e.pretty close to 70%. The others are pretty evenly distributed as well.

$\endgroup$

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.