[R] chi square residuals
Fred Jean
Frederic.Jean at univ-brest.fr
Mon Jul 1 12:29:23 CEST 2002
dear list,
I'm a newbie with R but it seems very interesting to me.
First, to train myself and students, I'd like to use it for teaching labs next
year.
one of my labs deals with the barn owl predation in my region. tudents have to
work on a contingency table tytogrp :
station1 station2 station3 ...
n1,1 n1,2 n1,3 ...
n2,1 n2,2 n2,3 ...
n3,1 ... ... ...
each column being a station and each row being a prey species.
first, they have to manage with a chi square test for heterogeneity.
I found how to manage that using chisq.test from package ctest
the main problem for me at this first step is to find a way to automatically
regroup rows just using a criterion like "expected < 5" ; I didn't succeed for
this trick yet.
second, students have to calculate the normalized residuals of the
chisq.test according to :
((obs-exp) / sqrt(exp)) / ((1-actual.row.sum / N)*(1-actual.col.sum / N))
with :
obs = observed freq
exp = expected freq
N = sum(obs)
actual.row.sum=sum of freq in the row
actual.col.sum=sum of freq in the column
and I don't succeed in trying to calculate these 2 last parameters....
here is the code I wrote, inspired by an email from Mark Myatt on 16 Apr 2001
"twoWay" <- function(x=NA, y=NA, userDefined=NA ) {
#
if (is.na(userDefined)){
result <- chisq.test(table(x,y))
}
else{
result <- chisq.test(userDefined)
}
#
print(result)
obs <- result$observed
exp <- result$expected
chi.table <- ((obs - exp)^2)/exp
row.sum <- apply(obs,1,sum)
col.sum <- apply(obs,2,sum)
N <- sum(obs)
#
fullArray <- cbind(obs,row.sum)
fullArray <- rbind(fullArray,c(col.sum,N))
rownames(fullArray) <- c(rownames(obs), "Total")
colnames(fullArray) <- c(colnames(obs), "Total")
#
# following doesn't work
# res.norm <- ((obs-exp)/sqrt(exp))/((1-row.sum/N)*(1-col.sum/N))
#
return(list(Complet=fullArray,Expected=exp,Chi=chi.table)) # add res.norm
}
thanks for any help (and sorry for my poor english)
----------------------------------------------------
Fred JEAN - UMR CNRS 6539 / LEMAR
Univ. Bretagne Occidentale - Institut Universitaire Européen de la Mer
Place Nicolas Copernic F-29280 PLOUZANE
Pho:+33 (0)2 98 49 86 38 // Fax:+33 (0)2 98 49 86 45
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list