Attempt to use tryCatch in an apply function in R

Viewed 34

The dataset is

 structure(list(`total primary - yes RS` = c(0L, 1L, 0L, 138L, 
101L), `total primary - no RS` = c(0L, 0L, 0L, 29L, 39L), `total secondary- yes rs` = c(0L, 
0L, 0L, 6L, 15L), `total secondary- no rs` = c(0L, 0L, 0L, 0L, 
7L)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"
))

Then from the dataset i run this to to get chisquare for each line. Though this works normally here it does not because some of the values contain zero's.

yes<-apply(sample, 1, function(x) tidy(chisq.test(matrix(x, ncol = 2)))) %>%

bind_rows

Though this script works i get an error message that says

at least one entry of 'x' must be positive

Is there a way to run the line of code i have but to skip the insufficient line?

1 Answers

As it is looping over the row, we can do

out <- apply(sample, 1, function(x) tryCatch(tidy(chisq.test(matrix(x, 
       ncol = 2))), error = function(err) tibble(statistic = NA)))



dplyr::bind_rows(out)
# A tibble: 5 x 4
#  statistic p.value parameter method                                                      
#      <dbl>   <dbl>     <int> <chr>                                                       
#1   NA       NA            NA <NA>                                                        
#2  NaN      NaN             1 Pearson's Chi-squared test                                  
#3   NA       NA            NA <NA>                                                        
#4    0.317    0.574         1 Pearson's Chi-squared test with Yates' continuity correction
#5    0.0166   0.898         1 Pearson's Chi-squared test with Yates' continuity correction
Related