Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tryCatch does not seem to return my variable

I'm trying to use tryCatch to generate a list of p-values there are several rows in the matrix that don't have enough observations for a t test. Here is the code I generated so far:

pValues <- c()
for(i in row.names(collapsed.gs.raw)){
  tryCatch({
    t <- t.test(as.numeric(collapsed.gs.raw[i,]) ~ group)
    pValues <- c(pValues, t$p.value)
  },
  error = function(err) {
    pValues <- c(pValues, "NA")
    message("Error")
    return(pValues)
  })}

It definitely throws an error [I put in the message("Error") line to confirm]. The problem is that the vector pValues doesn't have any "NA" in it, though it should.

Thanks in advance for your help!

like image 360
Aidan Quinn Avatar asked Sep 02 '25 17:09

Aidan Quinn


1 Answers

The pvalues in your function is a local variable. You might be able to fix this with <<-, but it would be preferred to have the function just return the one desired value and collect them outside the function with sapply. Perhaps something like (untested):

pValues <- sapply(rownames(collapsed.gs.raw), function(i) {
  tryCatch({
    t.test(as.numeric(collapsed.gs.raw[i,]) ~ group)$p.value
  },
  error = function(err) {
    message("Error")
    return(NA)
  })
})
like image 94
Aaron left Stack Overflow Avatar answered Sep 05 '25 07:09

Aaron left Stack Overflow