【问题标题】:prop.test row wise on a large data.frameprop.test 在大型 data.frame 上逐行
【发布时间】:2013-06-05 16:18:26
【问题描述】:

我有一个大约 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.

【问题讨论】:

  • 一般来说,总是试着看看一个函数是否被向量化,以及如何通过给它一些简短的样本向量并看看会发生什么。
  • prop.test 返回的列表中可能有一个组件值得关注,但不需要默认返回的长列表。
  • 有一个很好的答案here

标签: r


【解决方案1】:

您可以使用Map,它是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 在数据解析方面存在问题,因此可能难以识别哪个是哪个。

【讨论】:

    【解决方案2】:

    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 
    

    【讨论】:

    • 这不是 OP 所要求的。这是一个 4 样本测试。 OP 需要 3 个单独的 1 样本测试。
    猜你喜欢
    • 2014-10-05
    • 2013-01-24
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2018-02-08
    相关资源
    最近更新 更多