2015-02-09 26 views
1

如何创建具有彼此特定相关性的两列的数据集?我希望能够定义将要创建的值的数量并指定输出应具有的相关性。R:在r中创建具有特定相关性的数据集

问题是类似于此:Generate numbers with specific correlation

答案之一是使用:

out <- mvrnorm(10, mu = c(0,0), Sigma = matrix(c(1,0.56,0.56,1),, ncol = 2), 
       mpirical = TRUE) 

生产这样的输出:

  [,1]   [,2] 
[1,] -0.4152618 0.033311146 
[2,] 0.7617759 -0.181852441 
[3,] -1.6393045 -1.054752469 
[4,] -1.7872420 -0.605214425 
[5,] 0.9581152 2.511000955 
[6,] 0.5048160 -0.278329145 
[7,] 0.8656220 0.483521747 
[8,] -0.1385699 0.017395548 
[9,] 0.3261103 -0.932889606 
[10,] 0.5639388 0.007808691 

与下列相关表cor(out):

​​

但我想数据设置为含有较高,无负多远号码例如:具有1相关

 x y 
    1 5 5 
    2 20 20 
    3 30 30 
    4 100 100 

:远

x y 
    x 1 1 
    y 1 1 

具有更多的I意味着“更多”随机性和更大的价值,就像我上面的示例一样。

是否有(简单)的方式来归档类似的东西?

+1

“Pearson相关系数的一个关键数学特性是,分离两个变量的位置和比例变化是不变的。” =>为什么你不只是把'out'缩放到想要的范围内呢? – Jealie 2015-02-09 18:52:05

回答

2

相关性不受底层变量的线性变换的影响。所以最直接的方式得到你想要的可能是什么:

out <- as.data.frame(mvrnorm(10, mu = c(0,0), 
        Sigma = matrix(c(1,0.56,0.56,1),, ncol = 2), 
        empirical = TRUE)) 

out$V1.s <- (out$V1 - min(out$V1))*1000+10 
out$V2.s <- (out$V2 - min(out$V2))*200+30 

现在数据帧out已经“转移”列V1.sV2.s这都是非负和“大”。你可以使用任何你想要的数字,而不是上面代码中的1000,10,200和30。相关的答案仍然是0.56。

> cor(out$V1.s, out$V2.s) 
[1] 0.56 
+0

非常感谢,它可以像影像一样工作! 你也许知道我可以如何归档类似的东西,而只是整数(正整数)? – Deset 2015-02-09 19:10:15

+1

Deset,如果我的答案有帮助,请考虑接受或至少upvoting它。要制作数字整数,我不知道确切的方法,但可以通过简单地转换为大范围,然后舍入到最接近的整数来近似所需的相关系数。 – 2015-02-09 19:53:14

+1

注意舍入会稍微增加你的方差(例如'var(floor(rnorm(1000000)))'大约是1.08,而var(rnorm(1000000))大约是1.你可能会发现[this link] //www.sitmo.com/article/generating-correlated-random-numbers/)有帮助 – Jthorpe 2015-02-09 20:03:30

1

谢谢Curt F.这对我来说有助于生成一些模拟数据集。我添加了一些选项来指定约。 X和Y所需的平均值和范围。它还提供输出,以便您可以检查斜率和截距以及绘制点和回归线。

library(MASS) 
library(ggplot2) 
# Desired correlation 
d.cor <- 0.5 
# Desired mean of X 
d.mx <- 8 
# Desired range of X 
d.rangex <- 4 
# Desired mean of Y 
d.my <- 5 
# Desired range of Y 
d.rangey <- 2 
# Calculations to create multipliation and addition factors for mean and range of X and Y 
mx.factor <- d.rangex/6 
addx.factor <- d.mx - (mx.factor*3) 
my.factor <- d.rangey/6 
addy.factor <- d.my - (my.factor*3) 
# Generate data 
out <- as.data.frame(mvrnorm(1000, mu = c(0,0), 
          Sigma = matrix(c(1,d.cor,d.cor,1), ncol = 2), 
          empirical = TRUE)) 
# Adjust so that values are positive and include factors to match desired means and ranges 
out$V1.s <- (out$V1 - min(out$V1))*mx.factor + addx.factor 
out$V2.s <- (out$V2 - min(out$V2))*my.factor + addy.factor 
# Create liniear model to calculate intercept and slope 
fit <- lm(out$V2.s ~ out$V1.s, data=out) 
coef(fit) 
# Plot scatterplot along with regression line 
ggplot(out, aes(x=V1.s, y=V2.s)) + geom_point() + coord_fixed() + geom_smooth(method='lm') 
# Produce summary table 
summary(out)