Search code examples
riterationsimulation

Substituting number of simulations (n) in rnorm() using a list of predetermined values


I'm using rnorm() but instead of substituting the number of simulations n with just one variable, I would like to do this multiple times with n having predetermined values from a series of values. (In my project, I will need to do this 11,600+ times as there are 11,600+ predetermined values which I need to use rnorm() for - but the mean and standard deviation will be constant. To simplify everything for this discussion, I will just assume I have 10 predetermined values representing the number of simulations I would like to do.)

unit.cost <- rnorm(n=728, mean = 8403.86, sd = 1000)

Instead of just using "728" as the number of simulations (n), I would want to automatically substitute iteratively using these series of values: 728, 628, 100, 150, 99, 867, 934, 11, 67, 753. (I also want to use these series of values in the same order - and not just randomly using them, as the expected output should be a data frame listing the unit.cost using the predetermined values of n. Note that both mean and sd are constant.)

Upon search, it looks like for loop would be an ideal candidate to do this setup?


Solution

  • To get a data frame as the output, including the n parameter used, you could do the following:

    library(tidyverse)
    
    param_n <- c(728, 628, 100, 150, 99, 867, 934, 11, 67, 753)
    
    set.seed(1)
    
    cost_df <- map(param_n, \(param_n){
      tibble(
        param_n,
        unit_cost = rnorm(param_n, mean = 8403.86, sd = 1000)
        )
    }) |> 
      bind_rows()
    
    cost_df
    #> # A tibble: 4,337 × 2
    #>    param_n unit_cost
    #>      <dbl>     <dbl>
    #>  1     728     7777.
    #>  2     728     8588.
    #>  3     728     7568.
    #>  4     728     9999.
    #>  5     728     8733.
    #>  6     728     7583.
    #>  7     728     8891.
    #>  8     728     9142.
    #>  9     728     8980.
    #> 10     728     8098.
    #> # ℹ 4,327 more rows
    

    Created on 2024-04-22 with reprex v2.1.0