【发布时间】:2015-11-28 15:53:09
【问题描述】:
问题
在 R 中,我想创建长度为 L 的 n 变量,其关系由称为 cor_matrix 的 correlation matrix 给出。重要的一点是n 变量可能遵循不同的分布(包括连续分布和离散分布)。
相关帖子
从上面列出的third post 修改而来,以下是当所有n 变量都是连续的并且来自同一分布时的解决方案。
library(psych)
set.seed(199)
fun = function(cor_matrix, list_distributions, L)
{
n = length(list_distributions)
if (ncol(cor_matrix) != nrow(cor_matrix)) stop("cor_matrix is not square")
if (nrow(cor_matrix) != n) stop("the length of list_distributions should match the number of columns and rows of cor_matrix")
if (L<=1) stop("L should be > 1")
fit = principal(cor_matrix, nfactors=n, rotate="none")
loadings = matrix(fit$loadings[1:n, 1:n], nrow=n,ncol=n,byrow=F)
cases = t(sapply(1:n, FUN=function(i, L) list_distributions[[i]](L), L=L))
multivar = loadings %*% cases
T_multivar = t(multivar)
vars=as.data.frame(T_multivar)
return(vars)
}
L = 1000
cor_matrix = matrix(c (1.00, 0.90, 0.20 ,
0.90, 1.00, 0.40 ,
0.20, 0.40, 1.00),
nrow=3,ncol=3,byrow=TRUE)
list_distributions = list(function(L)rnorm(L,0,2), function(L)rnorm(L,10,10), function(L) rnorm(L,0,1))
vars = fun(cor_matrix, list_distributions, L)
cor(vars)
plot(vars)
但是,不能创建具有以下分布的相关变量
list_distributions = list(function(L)rnorm(L,0,2), function(L)round(rnorm(L,10,10)), function(L) runif(L,0,1))
vars = fun(cor_matrix, list_distributions, L)
cor(vars)
plot(vars)
【问题讨论】:
-
更具体地说,copula package。
标签: r math distribution correlation covariance