I plan to run 10,000 simulations on an existing dataset, and want to find the correlation coefficient of each simulation and save it into a dataframe (theoretically ending up with 10,000 correlation coefficients). How can I write code to run the simulation and print out the coefficient each time in a for loop?
This is the latest code I tried:
for (i in 1:10000) {
bnsamp <- data.frame(mvrnorm(n = 48, mu = mean_combined, Sigma = sigma))
colnames(bnsamp) <- c("Amyg_Avg", "Sys_Jus")
cor_coeff <- cor.test(x= bnsamp$Amyg_Avg, y= bnsamp$Sys_Jus,
method= "pearson", alternative= "two.sided")
cor_coef_est <- list(cor_coeff$estimate == i)
cor_coef_p <- list(cor_coeff$p.value == i)
coeff_list <- data.frame(cor_coef_est, cor_coef_p)
print(coeff_list)
}
Ultimately, my problem is how to loop the recalculation of the correlation and print it every single time (for later to be plotted into a distribution). Thank you!
Here are two ways of simulating the wanted values.
for
loop:replicate
From
help('replicate')
, my emphasis:Created on 2023-11-06