Rowwise simulation and export

Goal is to perform rowwise simulation and export the results.

Consider a simple example:

library(tidyverse)
tf <- tibble(a=c(-1,1),b=c(1,2))            ## parameters for simulation
tf1 <- tf %>% rowwise %>% mutate(           ## simulate 3 values each row
   c=list(rnorm(3,a,b))                     ##  results need to save in a list
)
print(tf1$c)                      

As shown here, tf1$c is a list of length 2, each includes 3 numeric values.

The simulation can be otherwise done using a for loop:

tf2 <- matrix(NA,2,3)
for(i in 1:2){
    tf2[i,] <- rnorm(3,tf2$a[i],tf2$b[i])
}

How to convert tf1$c into tf2? Any help is appreciated!

If you want the output in that matrix format, you could just skip tidyverse and use apply in this scenario:

t(apply(tf, 1, function(x) rnorm(3, x[1], x[2])))

If you want to use tidyverse, you could use this approach to add to what you've already done:

library(dplyr)
library(tidyr)
tf %>%
  rowwise() %>%
  mutate( ## simulate 3 values each row
    c = list(rnorm(3, a, b))  ##  results need to save in a list)
  ) %>%
  unnest_wider(col = c, names_sep = "_") %>%  # Get values out of the list column
  select(starts_with("c")) %>% # if you only want the "c" columns
  as.matrix() # If you want those columns in matrix form
1 Like

Elegant solutions. Thank you very much!

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.