Equivalent to R's sample(x,y,prob=) in Julia
Asked Answered
B

2

7

Julia-users: is there an equivalent to R's sample(x,y,prob=) to sample from a given set of values with weighted probabilities? The rand() function is equivalent to sample(x,y), but as far as I'm aware there's no option to add probability weights... Any help appreciated!

Bedlam answered 12/2, 2016 at 12:44 Comment(0)
B
9

OK - done a bit more digging and wsample from the Distributions package seems to be the answer:

using Distributions
wsample(population, weights, n)

Next time I'll look harder before posting!

Bedlam answered 12/2, 2016 at 13:0 Comment(0)
E
1

wsample exists also in the StatsBase.jl package (which I am not sure is a more recent addition compared to when the question was first answered)

If you go by StatsBase.jl you can also just use "sample":

using StatsBase
sample(population, Weights(weights), n) 

In both packages you can also set a random number generator and whether to take with replacement for both functions too.

Entoderm answered 2/11, 2022 at 8:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.