1

There are a few columns in my data where I have a ton of NA's so I can't run the HSD test on them. How do I get this loop to print the error and skip it, but continue looping over other columns where this test could work? The loop stops as soon as it gets to a column where too many NA's prevent me from doing an HSD test.

for (i in colnames(colu)){
  ANOVA <- aov(reformulate(c('block', 'loc'), i), data=S)
  ANOVA_SUMMARY <- summary(ANOVA)
  test <- HSD.test(ANOVA , "loc")
  df <- as.data.frame(test$groups) %>% 
    rownames_to_column(var = "Treatment") %>% 
    mutate(Treatment = factor (Treatment, levels = vector)) %>% 
    arrange(Treatment) 
  print(ANOVA_SUMMARY) 
  print(df)
  write.table(df, file = "S_output.txt", append=TRUE) 
}

Error in if (pvalue[k] <= 0.001) sig[k] <- "***" else if (pvalue[k] <=  : 
  missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In qtukey(1 - alpha, ntr, DFerror) : NaNs produced
2: In ptukey(abs(dif[k])/sdtdif, ntr, DFerror) : NaNs produced

1 Answers1

1

This is kind of tricky to answer without some sample data, but I think you might want to use something like trycatch().

This looks like a similar question to yours Use tryCatch skip to next value of loop upon error?

Below is a possible solution, but again, it's difficult to make sure if I don't have any sample data to work with. Hopefully this helps.

for (i in colnames(colu)){
  ANOVA <- aov(reformulate(c('block', 'loc'), i), data=S)
  ANOVA_SUMMARY <- summary(ANOVA)
  
  
  skip <- FALSE
  
  tryCatch(HSD.test(ANOVA , "loc"), error = function(e) {
    print(paste("Error in",i))
    skip <<- TRUE
  })
  
  if(skip) {next}
           
  test <- HSD.test(ANOVA , "loc")
  
  
  df <- as.data.frame(test$groups) %>% 
    rownames_to_column(var = "Treatment") %>% 
    mutate(Treatment = factor (Treatment, levels = vector)) %>% 
    arrange(Treatment) 
  print(ANOVA_SUMMARY) 
  print(df)
  write.table(df, file = "S_output.txt", append=TRUE)
  
}
KrutonCrab
  • 33
  • 6