Generating a random sample of elements from a list that includes a subset of the list - Mathematica Stack Exchange most recent 30 from mathematica.stackexchange.com 2019-09-23T18:55:14Z https://mathematica.stackexchange.com/feeds/question/46015 https://creativecommons.org/licenses/by-sa/4.0/rdf https://mathematica.stackexchange.com/q/46015 1 Generating a random sample of elements from a list that includes a subset of the list Cfg https://mathematica.stackexchange.com/users/13686 2014-04-13T18:34:21Z 2014-04-13T21:20:17Z <p>Imagine I have a list: <code>tList = {item1,item2,item3,item4,item5,item6,...}</code>, and I'd like to take a random sample of <code>numItems</code> elements of the list: <code>RandomSample[tList,numItems]</code>. Is there a way to specify the random sample should contain some subset of the elements in <code>tList</code>, e.g. <code>{item65,item70,item2,...}</code>? The hope is then that all of the elements from the random sample are returned scrambled, including the order of the elements in the subset?</p> https://mathematica.stackexchange.com/questions/46015/-/46025#46025 1 Answer by ciao for Generating a random sample of elements from a list that includes a subset of the list ciao https://mathematica.stackexchange.com/users/11467 2014-04-13T21:02:44Z 2014-04-13T21:02:44Z <p>I did not assume you won't have repeated elements in your base list (that is after all one way to weight sampling). </p> <pre><code>rsamp[list_, needs_, size_] := RandomSample[Join[needs, RandomSample[Fold[DeleteCases[#1, #2, 1, 1] &amp;, list, needs], Max[0, size - Length@needs]]], size]; </code></pre> <p>This works correctly for weighted base lists:</p> <pre><code>data = {"a", "w", "l", "a", "w", "l", "a", "w", "l", "a", "b", "c"} lst1 = {"a", "w", "b"}; rsamp[data, lst1, 5] (* {b,w,a,w,w} *) </code></pre> <p>This does not force the "needed" to be in the base, e.g., you can "inject" data into the sample:</p> <pre><code>rsamp[data, {"R", "A", "S"}, 6] (* {a,S,R,a,w,A} *) </code></pre> <p>Obviously, if you want to enforce that the "needed" data is a subset or strict subset, just add the trivial check.</p>