在多行(和多列)中将purrr与prop.test一起使用

时间:2018-11-13 13:16:36

标签: r purrr

类似于this问题,但不完全相同。

 result test1 test2 test3 test4
  a    13    12    12     8
  b     5     9    10     8
  c    39    24    30    29

如何将purr用于按结果将test1与test2:test4进行比较的行和列prop.tests?

手动,我猜每次测试看起来像这样:

结果:a,test1,test2:prop.test(c(13, 12), c(57, 45))

结果:c,test1,test4:prop.test(c(30, 29), c(57, 45))

1 个答案:

答案 0 :(得分:0)

# example data
dt = read.table(text = "
result test1 test2 test3 test4
a    13    12    12     8
b     5     9    10     8
c    39    24    30    29
", header=T, stringsAsFactors=F)


# function to get prop.test
# based on a row and two columns
GetTest = function(r, t1, t2) {

  prop.test(unlist(dt[dt$result == r, c(t1, t2)]),
            colSums(dt[,c(t1, t2)]))

}

# apply function
GetTest("a","test1","test2")

# 2-sample test for equality of proportions with continuity correction
# 
# data:  unlist(dt[dt$result == r, c(t1, t2)]) out of colSums(dt[, c(t1, t2)])
# X-squared = 0.047595, df = 1, p-value = 0.8273
# alternative hypothesis: two.sided
# 95 percent confidence interval:
#   -0.2274729  0.1502799
# sample estimates:
# prop 1    prop 2 
# 0.2280702 0.2666667