rfor-loopvectorerror-handlingpairwise.wilcox.test

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


In R, I am trying to create a vector with various p values, as in code below, but one of the four wilcox.test p values cannot be determined, because there is only one category. How can I make the code work so that it produces the vector with an NA when the wilcox.test cannot be performed?

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

Solution

  • You could use 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