0

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.

Hamed Said
  • 41
  • 1
  • 3
  • 1
    Bernoulli is a special case of binomial (with n = 1 trials), which is presumably why there is no built-in functions for Bernoulli variables. – John Coleman Nov 15 '20 at 14:21

2 Answers2

1

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.

Jonas
  • 1,760
  • 1
  • 3
  • 12
0

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))
SteveM
  • 2,226
  • 3
  • 12
  • 16