2015-05-17 34 views
1

我已經編寫了一些R代碼,它可以產生置信區間的限制以及每個置信區間覆蓋真實參數時的信息。我想要想象這個,但不知道如何。從數據框中繪製置信區間

confInt <- function(runs){ 
    result<-NULL 
    vleft<-NULL 
    vright<-NULL 

    for (i in 1:runs) { 
     data<-rnorm(1000) 
     n<-length(data) 
     a<-mean(data) 
     s<-sd(data) 
     error <- qnorm(0.975)*s/sqrt(n) 
     left <- a-error 
     right <- a+error 

     result[i] = left<0 & 0<right 
     vleft[i] = left 
     vright[i] = right 
} 
    data.frame(result,vleft,vright) 
} 


confInt(100) 

confidence

編輯:我發現使用ggplot2

confInt <- function(runs){ 
    x<-1:runs 
    mu<-NULL 
    sigma<-NULL 
    result<-NULL 
    vleft<-NULL 
    vright<-NULL 

    for (i in 1:runs) { 
     data<-rnorm(1000) 
     n<-length(data) 
     a<-mean(data) 
     mu[i]<-a 
     s<-sd(data) 
     sigma[i]<-s 
     error <- qnorm(0.975)*s/sqrt(n) 
     left <- a-error 
     right <- a+error 

     result[i] = left<0 & 0<right 
     vleft[i] = left 
     vright[i] = right 
} 
    data.frame(x,mu,sigma,result,vleft,vright) 
} 


df<-confInt(100) 

require(ggplot2) 

myplot<-ggplot(df, aes(x = x, y = mu)) + 
    geom_point(size = 2) + 
    geom_errorbar(aes(ymax = vleft, ymin = vright,colour=result*3)) 
myplot + theme_bw() 
summary(df) 

回答

1

有很多方法可以解決此問題的方法。下面,我用mapply來將每個置信區間的起點和終點輸入到segments

ci <- confInt(100) 

plot(y = c(0, 100), x = c(-.15,.15), type = 'n', ylab = "", 
    xlab = "", yaxt = 'n') 

with(ci, mapply(segments, x0 = vleft, x1 = vright, 
    y0 = 1:100, y1 = 1:100, col = (!result) + 1)) 

abline(v = 0, col = 'purple') 

enter image description here