Generate samples from bernoulli(p) using R

801 Views Asked by At

Using R, generate data from the Bernoulli(p), for various sample sizes (n= 10, 15, 20, 25, 30, 50, 100, 150, 200), for p = 0.01, 0.4, 0.8

I know how to do it for one case using the rbinom function. Like for the first scenario: rbinom(n=10, size=1, p=0.01).

My aim is to build a function that could compute all these scenarios preventing me to do all of them individually.

2

There are 2 best solutions below

0
Jonas On

The following function will give you a list of list. I tried to give them appopriate naming.

ff <- function(n,probs) {
  res <- lapply(n, function(i) {
    setNames(lapply(probs, function(p) {
      rbinom(n=i, size=1, p=p)
    }),paste0("p=",probs))
  })
  names(res) <- paste0("n=",n)
  res
}

Just call it like ff(n=c(10,15,20),probs = c(0.01,0.4,0.8)) and you will get a list of length 3 (for every n) which contains a list of length 3 (for every probability) with the vectors from the bernoulli-sample.

0
SteveM On

You can generate a dataframe of your np combinations with expand.grid and then use the map2 function of the tidyverse purrr package to generate a list of outputs for the np pairs:

library(tidyverse)

n <- c(10, 15, 20, 25, 30, 50, 100, 150, 200)
p <- c(0.01, 0.4, 0.8)
nps <- expand.grid(n = n, p = p)
samples <- 10
outlist <- map2(nps$n, nps$p, function(x, y) rbinom(samples, x, y))