r - 如何使用 for 循环更新协方差矩阵中的对角线?
问题描述
我已经使用 mvrnorms 创建了两个变量的模拟数据,我想在一个循环中关联这些变量 0、.5、.7 和 .9。但是每次我运行我的 for 循环时,我只能关联 0.9 处的值,而不能关联任何其他关联条件。
library(MASS) #library I needed to create simulated data with mvrnorms
num_iter <- 75
N <- 30 # setting my sample size
mu <- c(50.5, 10.5) # setting the std
R <- c(0,.5,.7,.9) # this vector defines the different correlation conditions I will add
# saving files
dir.create("simulated1data") # This creates a directory to store files
# performing 75 iterations and so there should be 75 data files in the folder I made
for(i in 1:num_iter){
for(j in 1:4){
cov <- matrix(c(1,R[j],R[j],1),2,2)
x <- mvrnorm(N,mu,cov)
write.table(x, file=paste("simulated1data/simdata_",i,"_",j,".txt",sep="")) # writing to separate txt file
}
}
据我了解,我的(对于 1:4 中的 j)没有适当地遍历我的 R 向量中的所有第 j 个值,这就是为什么 X 中的变量总是以 0.9 相关的原因。有谁知道如何解决这一问题?感谢您的时间!
解决方案
要分配 的值R
,请事先创建一个cov
矩阵并使用逻辑索引矩阵imat
。
第一个代码块就像问题一样。
library(MASS) #library I needed to create simulated data with mvrnorms
num_iter <- 75
N <- 30 # setting my sample size
mu <- c(50.5, 10.5) # setting the std
R <- c(0, 0.5, 0.7, 0.9) # this vector defines the different correlation conditions I will add
这是在我的系统上测试。
# saving files
dirsimdata <- "~/tmp/simulated1data"
dir.create(dirsimdata) # This creates a directory to store files
现在cov
和imat
矩阵。
# index matrix used to assign values from R
imat <- matrix(c(FALSE, TRUE, TRUE, FALSE), nrow = 2)
# start with all 1's
cov <- matrix(1, nrow = 2, ncol = 2)
最后,双for
循环。
# performing 75 iterations and so there should be 75 data files in the folder I made
for(i in 1:num_iter){
for(j in 1:4){
cov[imat] <- R[j]
x <- mvrnorm(N, mu, cov)
flname <- paste0("simdata_", i, "_", j, ".txt")
flname <- file.path(dirsimdata, flname)
write.table(x, file = flname) # writing to separate txt file
}
}
推荐阅读
- reactjs - deleteText 材料表反应对齐
- discord.js - Discord.js 通过 id 扮演角色
- firebase - 在 React Native Expo 中将 Firebase 数据传递到不同的屏幕
- amazon-s3 - 将文件从 AWS S3 复制到 Azure 存储归档层
- c# - 使用 Python .NET 从 C# 运行 Python 3.7
- python - 解码 utf8 文字 python
- jenkins - Jenkins 多分支管道如何工作?
- reactjs - 如何在 Prisma 中指定可选的查询过滤器?
- javascript - 在 json 文件中查找参数时出现问题
- python - 用于操作文本的 Python 脚本正在将 [ ]+ 写入文本文件而不是 [ \t]+