Chisq-test in R and tryCatch() function
1
0
Entering edit mode
2.1 years ago

Hi all,

I'm currently working with gene presence/absence data from 2 different groups. So I'm making a code to test their independence with chisq.test in R, but I don't know why tryCatch() function in R doesn't work I expected. Below is the code:

tryCatch(
    chi_result <- pairwiseNominalIndependence(table(temp_df), chisq=TRUE, method="bonferroni"),
    pval <- chi_result[["p.Chisq"]],
    pval_adj <- chi_result[["p.adj.Chisq"]],
    error=function(e){
      chi_result <- chisq.test(table(temp_df))
      pval <- chi_result[["p.value"]]
      pval_adj <- "INVALID INPUT"
      }
  )

What I intend is, pairwiseNominalIndependence() function makes an error, "Error in [.default(x, j, ) : subscript out of bounds", if every genes exist or absent, so I want to run chisq.test instead if pairwiseNominalIndependence() provokes an error cuz it results in nonsignificant p-value as an output anyway. If I run every each line by line, every code works perfectly, but if I run the tryCatch chunk, it doesn't run chisq.test(table(temp_df) and results in pval as NULL. Can someone give me any comment on it?

Thank you in advance

studio chisq R • 616 views
ADD COMMENT
0
Entering edit mode
2.1 years ago
Ram 43k

You're using tryCatch() wrong - the code to try should be in a block, and the code to execute on error should be in a separate block. You're doing the latter but not the former. See:

tryCatch(
    {
    chi_result <- pairwiseNominalIndependence(table(temp_df), chisq=TRUE, method="bonferroni");
    pval <- chi_result[["p.Chisq"]];
    pval_adj <- chi_result[["p.adj.Chisq"]];
    }, 
    error=function(e){
      chi_result <- chisq.test(table(temp_df))
      pval <- chi_result[["p.value"]]
      pval_adj <- "INVALID INPUT"
      }
  )

See here for a more comprehensive example.

As a side note, you could have Googled before posting and made sure you were using the right syntax.

ADD COMMENT

Login before adding your answer.

Traffic: 2842 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6