2012-12-29 57 views
1

与barplot和dotchart(来自调查包)相似,barNest(plotrix包)旨在为飞行中的svyby对象生成图,还绘制置信区间。但barNest.svymean不再处理调查数据。另一种方法是在调查绘图功能顶部绘制置信区间点图R调查置信区间图

library(survey) 
data(api) 
dclus1<-svydesign(id=~dnum, weights=~pw, data=apiclus1, fpc=~fpc) 
#just one variable   
a<-svyby(~api99, ~stype, dclus1, svymean) 
#several variables 
b<-svyby(~api99+api00, ~stype, dclus1, svymean) 
dotchart(b) 

虽然我不确定你会怎么做。如果有人解决这个问题,那么将它自动化是非常好的(通过创建一些适用于不同大小的svyby对象的代码),甚至可以将它合并到dotchart.svystat {survey}中。这将使组间图形比较容易得多!标准错误可以从b中提取或使用SE(b)。

+0

报告错误时,预计会提供足够的详细信息。代码在我的机器上运行良好。使用R 2.15.2,plotrix_3.4-5,survey_3.29,据我所知可以是所有当前版本。你甚至没有描述过什么“不工作”对你意味着什么。 –

回答

2

正确,因此您正试图在不知道如何处理该类的函数(barNest)中使用对象类(svyby),因为调查包和plotrix包不能很好地一起玩。幸运的是svyby对象dotchart方法是不是太多的代码,所以你可能只是想修改它..

# run your code above, then review the dotchart method for svyby objects: 
    getS3method('dotchart' , 'svyby') 

..和从,你可以学习它真的不是远远超出调用原dotchart功能(也就是说,在将b对象中包含的数据转换为矩阵后,不使用svyby对象,只是统计数据的常规集合)。现在你所要做的就是增加一个置信区间线。

置信区间宽度很容易通过运行

confint(b) 

获得的(更容易比使用SE(b))可以提取这些统计数据,以建立自己的barNestplotCI电话?

如果在点图上放置置信区间很重要,主要障碍是正确地打y坐标。在点图默认方法中挖掘..

getS3method('dotchart' , 'default') 

..你可以看到y坐标是如何计算的。削减到只有基本的内容,我想你可以使用这个:

# calculate the distinct groups within the `svyby` object 
    groups <- as.numeric(as.factor(attr(b , 'row.names'))) 

    # calculate the distinct statistics within the `svyby` object 
    nstats <- attr(b , 'svyby')$nstats 

    # calculate the total number of confidence intervals you need to add 
    n <- length(groups) * nstats 

    # calculate the offset sizes 
    offset <- cumsum(c(0, diff(groups) != 0)) 

    # find the exact y coordinates for each dot in the dotchart 
    # and leave two spaces between each group 
    y <- 1L:n + sort(rep(2 * offset , nstats)) 

    # find the confidence interval positions 
    ci.pos <- 
     rep(groups , each = nstats) + 
     c(0 , length(groups)) 

    # extract the confidence intervals 
    x <- confint(b)[ ci.pos , ] 

    # add the y coordinates to a new line data object 
    ld <- data.frame(x) 

    # loop through each dot in the dotchart.. 
    for (i in seq_len(nrow(ld))){ 

     # add the CI lines to the current plot 
     lines(ld[ i , 1:2 ] , rep(y[i] , 2)) 

    } 

但是这显然笨重,因为置信区间被允许去的方式在屏幕上。忽略了svyby类,甚至整个survey包一秒钟,找到我们实现dotchart很好地格式置信区间,我们可能会帮助你更多。我不认为survey包是你问题的根源:)

+0

安东尼,你是明星。非常感谢你。 – maycobra

+0

只需通过ld更改line.data即可。 – agstudy

+0

@agstudy done thanx :) –

0

向安东尼的最后一位(来自ld < -data.frame(x))添加一个新的点图(最小和最大值)解决了问题他概述。

ld <- data.frame(x) 
dotchart(b,xlim=c(min(ld),max(ld)))#<-added 
for (i in seq_len(nrow(ld))){ 
    lines(ld[ i , 1:2 ] , rep(y[i] , 2)) 
} 

但我同意安东尼:情节看起来不太好。非常感谢安东尼分享他的知识和编程技巧。置信区间也看起来不对称(这可能是正确的),特别是对于M api00。有没有人将此与其他软件进行比较? confit应该指定一个df(自由度)?

+0

'?svyciprop'列出了所有置信区间计算选项,包括指定'df ='并显示一个与stata完全匹配的示例..您可以阅读更多关于Dr. Lumley实现[exact stata match here](https://stat.ethz.ch/pipermail/r-help/2012-September/324464.html) –