prop.test函数在循环中

时间:2017-09-11 20:00:10

标签: r

我想在R中使用循环进行2个样本比例测试,并通过Health Center和Measure进行分割。下面是一个链接,显示我的数据如何设置的示例(该网站不允许我上传我的数据集的图像)

基本上,我想使用prop.test功能将健康中心A与措施A进行比较,并对我所有的健康中心(其中29个)和措施(其中14个)重复此操作。我只是不确定代码将循环这是什么,所以它做我想要的所有比例测试,并按我想要的方式分割它。

非常感谢任何帮助!

我继续删除所有的0。但是,我的代码工作但没有按我想要的方式分割数据。我希望它会被健康中心分开,然后通过测量,但它只是由健康中心分裂所以我有28个测量prop.test正在分析,而不仅仅是健康中心A与测量A.见下面的输出示例: Click here to see output

1 个答案:

答案 0 :(得分:0)

您可以使用此

执行split和prop.test
lapply(split(df, df$Health_Center), function(x) prop.test(as.matrix(cbind(x[,3], x[,4]-x[,3]))))

输出

$A1

        2-sample test for equality of proportions with continuity correction

data:  as.matrix(cbind(x[, 3], x[, 4] - x[, 3]))
X-squared = 1.713, df = 1, p-value = 0.1906
alternative hypothesis: two.sided
95 percent confidence interval:
 -0.28136975  0.04846377
sample estimates:
   prop 1    prop 2 
0.2307692 0.3472222 


$A2

        2-sample test for equality of proportions with continuity correction

data:  as.matrix(cbind(x[, 3], x[, 4] - x[, 3]))
X-squared = 0.12192, df = 1, p-value = 0.727
alternative hypothesis: two.sided
95 percent confidence interval:
 -0.1789668  0.1114439
sample estimates:
   prop 1    prop 2 
0.4800000 0.5137615 

输入数据

df <- data.frame(Health_Center=c("A1","A2","A1","A2"),
                 Measure=c("A","B","A","B"),
                 Numerator=c(15,48,25,56),
                 Denominator=c(65,100,72,109), stringsAsFactors=F)