【问题标题】:Generating correlated ordinal data生成相关的序数数据
【发布时间】:2014-12-09 01:00:18
【问题描述】:

我正在使用包 GenOrd 来生成相关的序数数据。基本思想是得到相关性为0.5的相关序数数据,现在我想重复整个代码1000次并保存相关性的结果,看看我能接近0.5的相关性,然后改变样本大小和边际概率,看看有什么变化。

library(GenOrd)
R<-matrix(c(1,0.5,0.5,1),2,2)
Marginal<-list(c(0.2,0.5,0.7,0.9),c(0.1,0.3,0.4,0.5))
DataOrd<-ordsample(100,Marginal,R)
correlation<-cor(DataOrd)
correlation[1,2] # 0.5269

【问题讨论】:

  • 你看过?replicate吗?
  • 我只想得到 1000 次模拟的结果,因此 1000 种不同的相关性,看看我能接近 0.5 的程度

标签: r simulation correlation


【解决方案1】:

这是一个简单的解决方案:

sim.cor <- function(R, Marginal, n, K)
{
   res <- numeric(length = K)
   for(i in 1:K)
      res[i] <- cor(ordsample(n, Marginal, R))[1,2]
   res
}

其中n 是样本大小,K 是您想要重复的次数。因此,在您的示例中,您可以调用此函数并将结果(大小为 K 的向量与相关性)保存在一个对象中:

set.seed(1234)
correlations <- sim.cor(R = R, Marginal = Marginal, n = 100, K = 1000)
mean(correlations)
[1] 0.5009389

一个更快更优雅的解决方案是使用 jaysunice3401 建议的 replicate 函数:

set.seed(1234)
n <- 100
correlations <- replicate(n = 1000, expr = cor(ordsample(n, Marginal, R))[1,2])
mean(correlations)
[1] 0.5009389

希望对你有帮助!

【讨论】:

  • 完美解决方案。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2016-10-27
  • 2010-12-15
  • 2013-04-08
  • 1970-01-01
  • 2018-08-08
  • 1970-01-01
  • 2015-03-08
  • 1970-01-01
相关资源
最近更新 更多