Bootstrap相关CI随着样本量的增加而增加

时间:2015-05-21 17:32:45

标签: r ggplot2 replication correlation confidence-interval

我想证明相关性周围95%置信区间的宽度如何随着样本量的增加而变化,从n = 10到n = 100,每轮5个样本的增量。我假设我们可以使用bootstrap函数来执行此操作并每次复制1000次。如何在R中完成? 看到: http://www.nicebread.de/at-what-sample-size-do-correlations-stabilize/

我们可以使用钻石数据:

data(diamonds)
x <- diamonds$price
y <- diamonds$carat

2 个答案:

答案 0 :(得分:3)

您可以自己添加图表和轴标题,但是此代码使用ggplot2和&#39;心理测量标准来执行我认为您正在寻找的内容。包:

library(ggplot2)
library(psychometric)

corSamp <- function(x) {
# return the correlation between price and carat on diamonds for a given sample size
  index <- sample(1:nrow(diamonds), x)
  carat <- diamonds$carat[index]
  price <- diamonds$price[index]
  return(cor(carat, price))
}

cors <- sapply(seq(5,100,5), corSamp)
lower <- sapply(1:20, function(i) return(CIr(r = cors[i], n = seq(5,100,5)[i], level = 0.95)[1]))
upper <- sapply(1:20, function(i) return(CIr(r = cors[i], n = seq(5,100,5)[i], level = 0.95)[2]))

myData <- data.frame(cbind(cors, lower, upper, seq(5,100,5)))

myPlot <- ggplot(myData, aes(x = V4, y = cors)) + geom_line() + geom_ribbon(aes(ymin = lower, ymax = upper), alpha = 0.5)

Sample size vs. correlation

此处V4是样本量。

答案 1 :(得分:1)

您可以使用sapply遍历样本大小,并为每个样本大小绘制1000个适当大小的随机样本,报告置信区间的平均宽度:

set.seed(144)
ci.widths <- sapply(seq(10, 100, 5), function(x) mean(replicate(1000, {
  r <- sample(nrow(diamonds), x, replace=TRUE)
  diff(cor.test(diamonds$price[r], diamonds$carat[r])$conf.int)
})))
plot(seq(10, 100, 5), ci.widths, xlab="Sample size", ylab="CI width")

enter image description here