0

I'm trying to make 4 objects with unique names that hold the output from multiple rbinom runs. Each set of rbinom runs uses different probabilities taken from a specific column of a different tibble. This is how I did it manually and I just want to recreate this with an iterative method.

collection_var_A <- rbinom(size = 20, n = 4 ,prob = (probs_tbl_A$value))
collection_var_B <- rbinom(size = 20, n = 4, prob = (probs_tbl_B$value))
collection_var_C <- rbinom(size = 20, n = 4, prob = (probs_tbl_C$value))
collection_var_D <- rbinom(size = 20, n = 4, prob = (probs_tbl_D$value))

The tibbles that contain the different $value columns look something like this:

probs_tbl_A <-  tibble(
    value = c(.56, .76, .85, .68), other = "other_stuff")

probs_tbl_B <-  tibble(
    value = c(.66, .72, .45, .39), other = "other_stuff")

probs_tbl_C <-  tibble(
    value = c(.56, .76, .85, .68), other = "other_stuff")

probs_tbl_D <-  tibble(
    value = c(.66, .72, .45, .39), other = "other_stuff")

I can get map() or map2() to iterate over the rbinom portion properly but it stores the output as a single list. I can't get it to iterate and simultaneously assign unique object names. I have tried supplying a list of the desired object names in different ways.

I feel like I'm missing a very easy way to do this.

user31189
  • 101
  • 1

2 Answers2

1

You can put the tibbles in a list and then use map

list_df <- mget(ls(pattern = "probs_tbl_.*"))
list_output <- purrr::map(list_df, ~rbinom(size = 20, n = 4 ,prob = (.$value)))
list_output

#$probs_tbl_A
#[1]  9 14 18 11

#$probs_tbl_B
#[1] 10 16 11  7

#$probs_tbl_C
#[1] 16 15 16 15

#$probs_tbl_D
#[1] 13 15  8  8

It will return you a list of numbers, if you want them as separate objects you can do

names(list_output) <- paste0("collection_var_", letters[seq_along(list_output)])
list2env(list_output, .GlobalEnv)

map can also be replaced with lapply to keep it in base R

lapply(list_df, function(x) rbinom(size = 20, n = 4 ,prob = (x$value)))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

We can use tidyverse methods

library(tidyverse)
map(mget(paste0("probs_tbl_", LETTERS[1:4])), ~ .x %>%
            pull(value) %>%
            rbinom(size = 20, n = 4, prob = .))
akrun
  • 874,273
  • 37
  • 540
  • 662