2

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)
      }
Sylvia Rodriguez
  • 1,203
  • 2
  • 11
  • 30

2 Answers2

3

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
Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
0

I just found a way:

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