How to return the value and the weight of sampled element?

I want to sample 1 element from values with specified weights:

values=[1,3,6,7,9]
weights=[0.1,0,4,0.3,0.1,0.1] 

I need to have access to the element sampled but also to its weight in weights. With the command

using StatsBase
sample(values,Weights(weights))

i only get the element sampled. If for example 7 is sampled, is it possible to have a result like (7,0.1), where 0.1 is the weight of 7 in weights? Thank you!

sample(collect(zip(values, weights)), Weights(weights))

should give you want you want.

2 Likes

Wonderful! That’s exactly what I need! Thanks!

Less memory intensive version could be

idx = sample(Weights(weights))
(values[idx], weights[idx])
3 Likes

This should be marked as the correct answer. Nicely done.

1 Like

Oh wow! I like this solution! Specially the less memory intensive part :slight_smile: I like both approaches anyway!

1 Like