Imagine I have a list: tList = {item1,item2,item3,item4,item5,item6,...}, and I'd like to take a random sample of numItems elements of the list: RandomSample[tList,numItems]. Is there a way to specify the random sample should contain some subset of the elements in tList, e.g. {item65,item70,item2,...}? 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?


1 Answer 1


I did not assume you won't have repeated elements in your base list (that is after all one way to weight sampling).

rsamp[list_, needs_, size_] := 
RandomSample[Join[needs, RandomSample[Fold[DeleteCases[#1, #2, 1, 1] &, list, needs], 
    Max[0, size - Length@needs]]], size];

This works correctly for weighted base lists:

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} *)

This does not force the "needed" to be in the base, e.g., you can "inject" data into the sample:

rsamp[data, {"R", "A", "S"}, 6]

(* {a,S,R,a,w,A} *)

Obviously, if you want to enforce that the "needed" data is a subset or strict subset, just add the trivial check.


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.