如何在无法确定 wilcox.test p 值时 return 一个 "NA" (R)

How to return an "NA" when wilcox.test p value cannot be determined (R)

在 R 中,我试图创建一个具有各种 p 值的向量,如下面的代码所示,但是无法确定四个 wilcox.test p 值之一,因为只有一个类别。如何使代码工作,以便在无法执行 wilcox.test 时生成带有 NA 的向量?

 set.seed(12345)
 df <- data.frame(
             a = c(rep("a", 5), rep("b", 4), rep("c", 6), rep("d", 10)),
             b = as.factor(c(1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0)),
             c = rnorm(25, 10, 6),
             stringsAsFactors = FALSE)
 x <- c("a", "b", "c", "d")
 vec <- vector()
 for (i in x) {
      vec <- c(vec, wilcox.test(c~b, data = df[df$a == i,])$p.val)
      }

你可以使用 tryCatch:

library(tidyverse)
df %>%
  group_split(a) %>% 
    lapply(., function(x) {
      tryCatch(expr = wilcox.test(formula = c~b, data = x)$p.value, error = function(e) NA)
    }) %>% unlist



[1] 1.000000       NA 1.000000 0.352381

我刚刚找到一个方法:

 for (i in x) {
     vec <- c(vec, tryCatch(wilcox.test(c~b, data = df[df$a == i,])$p.val, error=function(err) NA))
  }