'Creating a function in r to run a chi squared test

The goal is to create a chi squared test function with arguments dat and res.type="pearson" that returns an R list containing the test statistic, p-value, expected counts, residual type, and the residuals of that type, where the expected counts and the residuals are stored in two r × c matrices.

I think I have figured out how to get the expected counts and test statistic but can't figure out the res.type argument. The pearson residual equation is (o_ij-e_ij)/sqrt(e_ij) and the standard residual equation is (o_ij-e_ij)/sqrt(e_ij(1-n_i./n_..)(1-n_.j/n..)

Here is what I have so far

chisquared <- function(dat, res.type) {
expdata <- matrix(c((dat[4,1]*dat[1,4])/dat[4,4], 
   (dat[4,2]*dat[1,4])/dat[4,4], (dat[4,3]*dat[1,4])/dat[4,4], 
   (dat[4,1]*dat[2,4])/dat[4,4], (dat[4,2]*dat[2,4])/dat[4,4], 
   (dat[4,3]*dat[2,4])/dat[4,4], (dat[4,1]*dat[3,4])/dat[4,4], 
   (dat[4,2]*dat[3,4])/dat[4,4], (dat[4,3]*dat[3,4])/dat[4,4]), 
   nrow=3, ncol=3, byrow="T")
sqdist <- matrix(c((dat[1,1]-expdata[1,1])^2/expdata[1,1], 
(dat[1,2]-expdata[1,2])^2/expdata[1,2], (dat[1,3]- 
expdata[1,3])^2/expdata[1,3], (dat[2,1]- 
expdata[2,1])^2/expdata[2,1], (dat[2,2]- 
expdata[2,2])^2/expdata[2,2], (dat[2,3]- 
expdata[2,3])^2/expdata[2,3], (dat[3,1]- 
expdata[3,1])^2/expdata[3,1], (dat[3,2]- 
expdata[3,2])^2/expdata[3,2], (dat[3,3]- 
expdata[3,3])^2/expdata[3,3]), nrow=3, ncol=3, byrow="T")
ts <- sum(sqdist[1,1], sqdist[1,2], sqdist[1,3], sqdist[2,1], 
sqdist[2,2], sqdist[2,3], sqdist[3,1], sqdist[3,2], sqdist[3,3])
}

I'm sure there is an easier way to do this, other than the chisq.test function as I am not allowed to use it, so if anyone could provide some advice for that as well it would be appreciated

r


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source