• Chi square tests in R - [统计|Statistics]

    2008-07-03

    Tag:R

    R easily computes Chi-square tests for any supplied matrix.
    Reminder: R and matrices
    The basic R command for a matrix is to start with a list of elements(c(,,,)) and the number of rows nrow in the matrix.
    > args(matrix)
    function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)

    For example, if we have the 2x4 contingency table
    9   15   5   15
    4   12   10  4
    We express this as a matrix with the command
    > M<-matrix(c(9,4,15,12,5,10,15,4), nrow=2, byrow=F)
    It's always a good idea to check to see that you have correctly enter the matrix. Typing
    > M

    To perform Pearson's Chi-squared test, simply put the contingency table data into a matrix.
    > chisq.test(M)
    For the above table, R returns:
            Pearson's Chi-squared test
    data:  M
    X-squared = 7.9266, df = 3, p-value = 0.04755

    Note, however, that some of the cells of the table have values of 5 or less. In such cases, Fisher's exact test is better.
    > fisher.test(M)
            Fisher's Exact Test for Count Data
    data:  M
    p-value = 0.05133
    alternative hypothesis: two.sided

    ==========================
    批量计算:
    x=read.table("C:\...)
    d=nrow(x)
    z<-matrix(0,d,d)
    z
    for(i in 1:d)
    for(j in 1:d)
    z[[i,j]]<-chisq.test(x[,i],x[,j])$p.value
    round(z,3)
    write.table(z,file="R_tmp")

    List to Vector: unlist
    M<-matrix(unlist(x[i,]),nrow=2,byrow=T)


    历史上的今天: