If you examine the code below, I'm trying to run a simulation where the data is sampled every year for 10 years for 100 orders. The simulation works fine for the first 10 years of order 1, but when it comes to order 2 it tacks the value onto order 1, i.e., creates a vector rather than gives me a scalar. This messes up my output and I don't know how to fix it.
dat <- data.frame(cbind(rnorm(30,600,sd=100),rnorm(30,300,sd=50),rnorm(30,200,sd=50),rnorm(30,600,sd=100)))
colnames(dat) <- c("unused","apr","oct","used")
unused <- NULL
deduct <- NULL
carryover <- NULL
used <- NULL
apr <- NULL
oct <- NULL
available <- NULL
#_____________________________________ Sample Data _____________________________________________________
for (i in 1:100) { #increment for orders
for (k in 1:10){ #increment for years
if(k==1) {
subsample <- dat[sample(seq_along(dat[, 1]), size = 1,replace=TRUE), c("unused", "apr","oct","used")]
} else {
subsample <- dat[sample(seq_along(dat[, 1]), size = 1,replace=TRUE), c("apr","oct","used")]
}
if (k==1) unused[i] <-subsample$unused
apr[i] <- subsample$apr
oct[i] <- subsample$oct
used[i] <- subsample$used
#print(subsample)
#_____________________________________ Use Data _____________________________________________________
if (unused[i] > 200) {
deduct[i] <- unused[i]-200
carryover[i] <- 200
available[i] <- carryover[i]+apr[i]+oct[i]
}
if (unused[i] <= 200) {
deduct[i] <- 0
carryover[i] <- unused[i]
available[i] <- carryover[i]+apr[i]+oct[i]
}
#_____________________________________ Create unused for next year _______________________________
unused <- available-used
}
}
Aucun commentaire:
Enregistrer un commentaire