简体   繁体   中英

Two way tables and the Chi square Test in R

I am currently working on a R-project for school. I have a question concerning the project. I have to print a two way tables, and each cell of my table should contain the result of a Chi square test.

For example :

我的两人桌

For example, the 0.7 is the result of the chi square test between Orange and Apple.

I know how to do the chi square test between two variables :

chisq.test(c(data_frame$Apple, data_frame$Orange))

Then I tried to print the two-way tables :

list <- c("Apple", "Orange", "Grappe")
for (element in list) {
   for (element2 in list) {
      chisq.test(c(data_frame$element, data_frame$element2))
   }
}

But it's not working, I have an infinite loop.

Can someone help me with this problem ? I am new to R Also, sorry for my English

Without seing data_frame it's not possible to know if the following code does what you want, but here it goes.
First of all, I've changed the name of the vector to mylist since list is an R function.

mylist <- c("Apple", "Orange", "Grappe")

pval <- lapply(mylist, function(x){
    lapply(mylist, function(y){
        if(x != y) {
            chisq.test(data_frame[[x]], data_frame[[y]])$p.value
        }
    })
})
pval

This will only produce the p-values, if you want the full output of chisq.test you would use

result <- lapply(mylist, function(x){
    lapply(mylist, function(y){
        if(x != y) {
            chisq.test(data_frame[[x]], data_frame[[y]])
        }
    })
})

This produces a nested list of lists, each of the elements of the nested lists is an object of class htest , the ones returned by hypothesis testing in R.

Try this

list <- c("Apple", "Orange", "Grappe")
while (element in list) {
   while (element2 in list) {
      chisq.test(c(data_frame$element, data_frame$element2))
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM