Skip to content
Prev 10741 / 398502 Next

contingency tables in R

Kurt Hornik <Kurt.Hornik at ci.tuwien.ac.at> writes:
Most of this is in table() and chisq.test(). Here is an example from
RWeb:

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)
  observed <-result$observed
  expected <- result$expected
  chi.table <- ((observed - expected)^2)/expected
  row.sum <- apply(observed,1,sum)
  col.sum <- apply(observed,2,sum)
  N <- sum(observed)

  ## put in the marginals and names  ... create fullArray
  fullArray <- cbind(observed,row.sum)
  fullArray <- rbind(fullArray,c(col.sum,N))
  rownames(fullArray) <-  c(rownames(observed), "Total")
  colnames(fullArray) <- c(colnames(observed), "Total")

  ## make the tables of proportions
  proportion <- fullArray/N
  row.proportion <- fullArray/c(row.sum,N)
  col.proportion <- t(t(fullArray)/c(col.sum, N))

  return(list(fA=fullArray, e=expected, ct=chi.table, p=proportion,
rp=row.proportion, cp=col.proportion))
}

This needs a nice print() method.
And fisher.test(). Have a look at my intro text
(http://www.myatt.demon.co.uk) for examples of calculating RRs and ORs
in tabulating functions.
Or by().
Yes, the key bits are all there. It should not take to long to get a
function that meets your own needs.

Mark



--
Mark Myatt


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._