Use purrr with prop.test over multiple rows (and columns)

Viewed 495

Similar to this question, but not exactly the same.

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

How can I use purr for row and columnwise prop.tests comparing test1 to test2:test4 by result?

Manually I guess it would look like this for each test:

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

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

1 Answers
# 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 
Related