Run a Monte Carlo for each row of a data frame in R

陌路散爱 提交于 2021-01-29 09:30:15

问题


I am trying to run a Monte Carlo for each row of a data frame using R.

library(tidyverse)
Group.ID <- c('A','B','C')
Start.Amount <- c(90.2, 11.7, 37.8)
Mean <- c(0.0005106365,0.0006589744,0.000444903)
SD <- c(0.01587259,0.02358892,0.02070972)

summary <- data.frame(Group.ID, Start.Amount, Mean, SD)

For instance I am trying to run a Monte Carlo for Group.ID A then run a different simulation for Group.ID B and so on.

I am running a single Group.ID with the following code.

#### Monte Carlo parameters ####
days.to.fourth.time <- 50 # number of days looked at

set.seed(13) # reproducible

N<-200 # number of trials

#### creates simulation data ####
# make blank matrix
monte.carlo.matrix<-matrix(nrow=days.to.fourth.time,ncol=N)

# puts the start value
a <- summary[1,2]

for(j in 1:ncol(monte.carlo.matrix)){
  monte.carlo.matrix[1,j] <- a 
  
  # gets mean and sd
  mu <- summary[1,3]
  sig <- summary[1,4]
  
  # multiples the previous value by mean and sd
  for(i in 2:nrow(monte.carlo.matrix)){
    monte.carlo.matrix[i,j]<-monte.carlo.matrix[i-1,j]*exp(rnorm(1,mu,sig))
  }
}

#### make simulation output table  ####
MC.Results<-cbind(1:(days.to.fourth.time),monte.carlo.matrix) #makes matrix of Monte Carlo with first column "Day"
name<-str_c("Simulation ",seq(1,500))  # names the columns "Simulation #"
name<-c("Day",name) # adds a column "Day"

MC.Results<-as_tibble(MC.Results) # converts matrix to tibble
colnames(MC.Results)<-name # labels columns

How would I go about coding to allow for a Monte Carlo to run for each row, while saving each MC.Result as a data frame uniquely labeled? Ideally the data frame would be labeled something like MC.Result.A.

Thanks for your help!

来源:https://stackoverflow.com/questions/63837147/run-a-monte-carlo-for-each-row-of-a-data-frame-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!