2

我有一个大约 1000 行和 2 列的 data.frame。我想执行prop.test(k,n),其中k ==我的data.frame的Column1和n ==我的data.frame的Column2。

例如:

 Column1(k)   Column2(n)      
     60         500    
     50         500     
     70         500    
     40         500     

我想为每一行执行 prop.test (k, n) 。例如:

prop.test(60, 500)
prop.test(50, 500)
prop.test(70, 500)

等等。由于我有大约 1000 行,因此我显然无法通过每行手动执行 prop.test。如何编写一个函数,每次都将每一行作为输入并执行 prop.test?

非常感谢,

E.

4

2 回答 2

2

您可以使用Mapwhich 是一个包装器mapply

dfr <- data.frame(k=c(60,50,70,40),n=rep(500,4))
Map(prop.test,x=dfr$k,n=dfr$n)
[[1]]

        1-sample proportions test with continuity correction

data:  dots[[1L]][[1L]] out of dots[[2L]][[1L]], null probability 0.5 
X-squared = 287.282, df = 1, p-value < 2.2e-16
alternative hypothesis: true p is not equal to 0.5 
95 percent confidence interval:
 0.09348364 0.15251247 
sample estimates:
   p 
0.12 


[[2]]

        1-sample proportions test with continuity correction

data:  dots[[1L]][[2L]] out of dots[[2L]][[2L]], null probability 0.5 
X-squared = 318.402, df = 1, p-value < 2.2e-16
alternative hypothesis: true p is not equal to 0.5 
95 percent confidence interval:
 0.07580034 0.13052865 
sample estimates:
  p 
0.1 

...

请注意,prop.test数据解析有问题,因此很难识别哪个是哪个。

于 2013-06-05T16:35:37.330 回答
1

prop.test是矢量化的。你可以这样做 :

   prop.test(col1, col2)

例如 :

dat <- data.frame(Column1 =c( 83, 90, 129, 70 ),Column2= c( 86, 93, 136, 82 ))
> prop.test(dat$Column1,dat$Column2)

    4-sample test for equality of proportions without continuity correction

data:  dat$Column1 out of dat$Column2
X-squared = 12.6004, df = 3, p-value = 0.005585
alternative hypothesis: two.sided
sample estimates:
   prop 1    prop 2    prop 3    prop 4 
0.9651163 0.9677419 0.9485294 0.8536585 
于 2013-06-05T16:27:37.063 回答