最近我一直在研究统计模拟,在生成随机数据以匹配相关矩阵的规格后,我想将每一列转换为具有特定的均值和标准差。我在下面的代码中成功地做到了这一点,但它非常混乱,我想知道是否有更有效的方法来做到这一点。
#Input Correlation Matrix
sigma <- matrix(c(1.00, -0.03, 0.39, -0.05, -0.08,
-0.03, 1.00, 0.07, -0.23, -0.16,
0.39, 0.07, 1.00, -0.13, -0.29,
-0.05, -0.23, -0.13, 1.00, 0.34,
-0.08, -0.16 ,-0.29, 0.34, 1.00), nr=5, byrow=TRUE)
rownames(sigma) <-c("Exercise", "Hardiness", "Fitness", "Stress", "Illness")
colnames(sigma) <-c("Exercise", "Hardiness", "Fitness", "Stress", "Illness")
#The Choleski Decomposition Random Data Generator
N <- 373
L = chol(sigma)
nvars = dim(L)[1]
# Random variables that follow the sigma correlation matrix
r = t(L) %*% matrix(rnorm(nvars*N), nrow=nvars, ncol=N)
r = t(r)
sample = as.data.frame(r)
#Transform to appropriate means and standard deviations
sample$Exercise <- c(((sample$Exercise - mean(sample$Exercise))/sd(sample$Exercise))*66.5+40.9)
sample$Hardiness <- c(((sample$Hardiness - mean(sample$Hardiness))/sd(sample$Hardiness))*3.8+0)
sample$Fitness <- c(((sample$Fitness - mean(sample$Fitness))/sd(sample$Fitness))*18.4+67.1)
sample$Stress <- c(((sample$Stress - mean(sample$Stress))/sd(sample$Stress))*6.7+4.8)
sample$Illness <- c(((sample$Illness - mean(sample$Illness))/sd(sample$Illness))*624.8+716.7)
sample <- as.data.frame(sample)
这是我希望简化的最后一段标记为“转换为适当的平均值和标准差”的代码。以下是每个列变量的均值和标准差(按顺序):
means <-c(40.9, 0, 67.1, 4.8, 716.7)
sdevs <-c(66.5, 3.8, 18.4, 6.7, 624.8)
感谢您的帮助和愿意分享您的知识!我期待听到您的意见!