There's a number of ways to do this. One is using apply
to go through each line (MARGINE = 1
) and then extract whatever part of the output you want (I use lapply
to climb through each list element).
xy <- data.frame(obs1 = c(3,12,45,2,7,17,5), obs2 = c(2,10,53,13,12,15,5))
result <- apply(X = xy, MARGIN = 1, FUN = chisq.test)
Warning message:
In FUN(newX[, i], ...) : Chi-squared approximation may be incorrect
# see where p-value is stored
str(chisq.test(xy[1, ]))
List of 9
$ statistic: Named num 0.2
..- attr(*, "names")= chr "X-squared"
$ parameter: Named num 1
..- attr(*, "names")= chr "df"
$ p.value : num 0.655 # thar she blows
$ method : chr "Chi-squared test for given probabilities"
$ data.name: chr "xy[1, ]"
$ observed : num [1:2] 3 2
$ expected : num [1:2] 2.5 2.5
$ residuals: num [1:2] 0.316 -0.316
$ stdres : num [1:2] 0.447 -0.447
- attr(*, "class")= chr "htest"
Warning message:
In chisq.test(xy[1, ]) : Chi-squared approximation may be incorrect
unlist(lapply(result, "[", "p.value"), use.names = FALSE)
[1] 0.654720846 0.669815358 0.419020334 0.004508698 0.251349109 0.723673610 1.000000000