R's sample() in C++

Asked 2 years ago, Updated 2 years ago, 55 views

I think R has a function called sample() that allocates probability to each vector x (sample(x,size,replace=FALSE,prob=NULL)). Is it possible to do the same thing in C++ (for example, by using a library)?
The Eigen library seemed to allocate only a uniform probability to all elements, but could it be done with ingenuity?

c++

2022-09-29 20:25

1 Answers

If you look for a library, you'll find it, but I think it's faster to implement it myself than to look for it.
I don't know if the behavior of sample() is simulated correctly, but I tried implementing it as follows.

The code below has been verified to work in visual studio 2015 community.

#include<random>
# include <vector>
# include <numeric>
# include <iostream>

Simulate the behavior of sample() in //R
template<class T>
std::vector<T>sample(const std::vector<T>&vec,const int&num_samples)
{
    // GENERATOR FOR INITIAL VALUE OF RANDOM NUMB
    std::random_device rd;

    // random number generator
    std::mt19937 generator(rd());

    // generation of uniform distribution
    std::uniform_int_distribution<int>distribution(0,vec.size()-1);

    // generation of return value
    std::vector<T>return_val(num_samples);

    // All we have to do is add results.
    for (auto&em:return_val)
    {
        elem=vec [distribution(generator)];
    }

    return(return_val);
}

Simulate the behavior of sample() in //R
template<class T>
std::vector<T>sample(const std::vector<T>&vec, const int&num_samples, const std::initializer_list<double>&list)
{
    if(vec.size()!=list.size())
    {
        throw "invalid size\n";
    }

    // GENERATOR FOR INITIAL VALUE OF RANDOM NUMB
    std::random_device rd;

    // random number generator
    std::mt19937 generator(rd());

    // generation of uniform distribution
    std::discrete_distribution<int>distribution(list);

    // generation of return value
    std::vector<T>return_val(num_samples);

    // All we have to do is add results.
    for (auto&em:return_val)
    {
        elem=vec [distribution(generator)];
    }

    return(return_val);
}

int main()
{
    // Check if it works
    std::vector<int>num(5);

    std::iota(num.begin(), num.end(), 0);

    std::cout<<"If the probability has a specific gravity:\n";

    {
        autovec=sample(num,10,{0.5,2.1,3,0.4,10.0});

        // output
        for (auto&em:vec)
        {
            std::cout<<elem<<";";
        }

        std::cout<<std::endl;
    }

    std::cout<<"For uniform probabilities:\n";

    {
        autovec=sample(num,10);

        // output
        for (auto&em:vec)
        {
            std::cout<<elem<<";";
        }

        std::cout<<std::endl;
    }

    return 0;
}


2022-09-29 20:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.