tryCatch似乎没有返回我的变量 [英] tryCatch does not seem to return my variable
问题描述
我试图使用tryCatch生成一个p值的列表,矩阵中有几行没有足够的t检验观察结果。这是我迄今为止生成的代码:
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)
})}
它肯定会抛出一个错误[我放入消息(错误)行确认]。问题是矢量pValues没有任何NA,虽然它应该。
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.
提前感谢您的帮助!
推荐答案
您的函数中的 pvalues
是一个局部变量。您可能可以用< < -
来解决这个问题,但最好让函数只返回一个所需的值,并将其收集到函数外部, code> sapply 。可能是(未经测试):
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)
})
})
这篇关于tryCatch似乎没有返回我的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!