# In \`StatsBase.jl\`, is it possible for \`sample\` to not return vectors?

**URL:** <https://discourse.julialang.org/t/in-statsbase-jl-is-it-possible-for-sample-to-not-return-vectors/85164>\
**Category:** General Usage\
**Tags:** package\
**Created:** [August 2, 2022, 1:27pm UTC](https://discourse.julialang.org/t/in-statsbase-jl-is-it-possible-for-sample-to-not-return-vectors/85164 "2022-08-02T13:27:14Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![drelatgithub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/drelatgithub/32/36402_2.png) [@drelatgithub](https://discourse.julialang.org/u/drelatgithub)\
**Post date:** [August 2, 2022, 1:27pm UTC](https://discourse.julialang.org/t/in-statsbase-jl-is-it-possible-for-sample-to-not-return-vectors/85164/1 "2022-08-02T13:27:14Z")

</div>

In `StatsBase.jl`, using `sample` function with many samples returns a vector with all the sample results. I might be overlooking the documents, but I’m looking for a way to “consume” each sample result in-place without building the resulting vector, while still enjoying the benefit of preprocessing. My use case is similar to the following:

```julia
nitems = 100
nsamples = 10000
w = Weights(rand(nitems))
counts = zeros(nitems)

# Is it possible to not generate the 10000-element intermediate vector?
for eachsample in sample(1:nitems, w, nsamples)
    counts[eachsample] += 1
end

# Alternatively, this seems not to utilize preprocessing.
for _ in 1:nsamples
    counts[sample(1:nitems, w)] += 1
end

```

Is there a way to achieve it? Thank you!

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [August 2, 2022, 1:54pm UTC](https://discourse.julialang.org/t/in-statsbase-jl-is-it-possible-for-sample-to-not-return-vectors/85164/2 "2022-08-02T13:54:46Z")

</div>

Have you considered the `sample!` function? [Sampling from Population · StatsBase.jl](https://juliastats.org/StatsBase.jl/stable/sampling/#StatsBase.sample)!

This function reuses a single pre-allocated output array. But you’ll need one allocation still.

---

<div class="post-metadata">

**Author:** ![drelatgithub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/drelatgithub/32/36402_2.png) [@drelatgithub](https://discourse.julialang.org/u/drelatgithub)\
**Post date:** [August 2, 2022, 2:34pm UTC](https://discourse.julialang.org/t/in-statsbase-jl-is-it-possible-for-sample-to-not-return-vectors/85164/3 "2022-08-02T14:34:28Z")

</div>

Thanks! Indeed, that function also requires an array with the size of output. It is still beneficial if I want to do such sampling multiple times as I can reuse the buffer.
