Search code examples
rprobabilitysampling

Randomly generate a subset data based on probabilities


This is about the resampling questions. I want to generate a species list fro a random sample of n individuals based on the species probabilities.

For example: there are 3 species c("sp.1", "sp.2", "sp.3"),and their abundance is c(1,2,3). I want to how the species list if i randomly pick up 2 individuals. Repeat many times.

Many thanks!


Solution

  • Just add the probabilities into sample using prob

    sample(c("sp.1", "sp.2", "sp.3"), 2, prob=c(1,2,3))
    

    to repeat, you could wrap in replicate, e.g. 100 times:

    replicate(100, sample(c("sp.1", "sp.2", "sp.3"), 2, prob=c(1,2,3)))