【问题标题】:Attempt to use tryCatch in an apply function in R尝试在 R 的应用函数中使用 tryCatch
【发布时间】:2021-04-16 20:32:56
【问题描述】:

数据集是

 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"
))

然后我从数据集中运行它以获取每行的卡方。虽然这在这里正常工作,但它不是因为一些值包含零。

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

绑定行

虽然这个脚本有效,但我收到一条错误消息,上面写着

at least one entry of 'x' must be positive

有没有办法运行我拥有的代码行但跳过不足的行?

【问题讨论】:

    标签: r apply chi-squared


    【解决方案1】:

    因为它在行上循环,我们可以这样做

    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
    

    【讨论】:

      猜你喜欢
      • 2018-10-02
      • 2015-10-27
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多