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
```

- geom_area stacks areas by default
- how to display factor in scientific notation
- running a PCA on a RasterStack in R
- How can I extract a value from a dataframe based on a range of values?
- how to set for loop with two conditions
- Confidence Interval for Some (But Not All) Interaction Terms in a Polynomial Interacted with a Binary Treatment
- Avoiding crazy lines while mapping in r
- Overlay points on top of violin plot
- Add percentage labels to geom_col()
- How to place a js inside a swiper with appendTo()?
- How to make a single plot from two dataframes with ggplot2
- Error in installing "TopicModels" package in Google Colab
- Identify connected subnetworks (R-igraph)
- Adding labels to geom_col()
- Legend title in ggplot2
- R list files with multiple conditions
- R - getting count of maximum-sized sub-group when summarising at prior group_by level
- Problems when running GDC_prepare in R
- Filtering files with names starting with a specific string
- Mutate a vector within a pipe chain
- How to sum a variable by group
- Using hex code to change text color in RMarkdown PDF (R)
- How to Remove Degree and Cardinal Direction Symbols from ggplot Coordinate Axes
- rstan and brms cause R and RStudio session abort
- How to change the plot background color generated by plot(effect(...)) in grey with white grid in R？
- SQL query on arrow duckdb workflow in R
- Venn diagram with duplicated elements
- R- Filter by time closest to midnight
- Difference between rlm() and lm_robust
- Is there a way to combine sorting an rhandsontable and removing from an rhandsontable?