help with drawing samples and storing in a tibble using rowwise() and a function


I have 2 similar workflows and the first is working but the 2nd is not. I am looking for help with getting the 2nd to work but also in understanding why the 1st and 2nd are different.

Workflow 1 (this works as intended):

  • have tibble with values for mean and standard deviation
  • have function that draws from rnorm
  • use rowwise() and mutate to generate draws from each pair of mu/sd by row and store in new column, then unnest

Workflow 2 (this one doesn't work)

  • have tibble with various values of 2 descriptive variables and 1 variable with values of interest
  • have function that filters a tibble by descriptive variables then draws randomly from the values of interest column
  • use rowwise() and mutate to generate draws from values column after filtering by each pair of var_a and var_b by row and store in new column, then unnest

example below:


#workkflow 1 below (this one works)

#tibble with mus and sigmas
p_tbl <- tibble(
  mu = c(3, 5, 4, 3),
  sigma = c(.5, .8, .3, .6)

#function to draw from mu and sigma
draw_fcn <- function(tbl, n, mu, sigma) {
  draws <- rnorm(n = n, mean = mu, sd = sigma)

#use rowwise and mutate and fcn to store draws in new col then unnest it
resultant_tbl <- p_tbl %>%
  rowwise() %>%
  mutate(results = list(draw_fcn(
    n = 5,
    mu = mu,
    sigma = sigma
  ))) %>%

#workkflow 2 below (this one doesn't work)##################################

#tibble with descriptive vars a and b and values of interest
v_tbl <- tibble(
  var_a = rep(c("A", "B", "C"), 2),
  var_b = rep(c("X", "Y", "Z"), 2)
) %>%
  expand.grid() %>%
  mutate(values = runif(n = 36, min = 0, max = 10))

#fcn to filter and then draw randomly from remaining values of interest
other_draw_fcn <- function(tbl, n, filter_val_1, filter_val_2) {
  temp <- tbl %>%
    filter(var_a == filter_val_1) %>%
    filter(var_b == filter_val_2)

  store <- sample(x = temp$values, size = n, replace = TRUE)

#trying same workflow as with method 1 to apply function across each combination of var_a and var_b rowwise [doesn't work]
other_resultant_tbl <- v_tbl %>%
  rowwise() %>%
  mutate(results = list(other_draw_fcn(
    n = 5,
    filter_val_1 = var_a,
    filter_val_2 = var_b
  ))) %>%

#testing that function works on its own (it does)
other_draw_fcn(tbl = v_tbl, n = 5, filter_val_1 = "A", filter_val_2 = "Y")

Thank you for any help you can provide!

in draw_fcn you define tbl param that you dont use. (and dont need to use)
in other_draw_fcn you similarly dont use it, but you should (to make your code work with minimum edits)

other_resultant_tbl <- v_tbl %>%
  rowwise() %>%
  mutate(results = list(other_draw_fcn(v_tbl,
    n = 5,
    filter_val_1 = var_a,
    filter_val_2 = var_b
  ))) %>%

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.