要让程序在出现这类错误时继续执行,并且在结果中返回NA
值,你可以使用tryCatch
函数来捕获和处理这些异常
results <- foreach(m = 1:length(df_gene),
.packages = "tidyverse",
.combine = rbind) %dopar% {
mRNA_name = df_gene[m]
res2 = data.frame()
for (n in 1:length(lncRNA$id)) {
lncRNA_name = lncRNA$id[n]
data = df_gene_TPM[,c("sample", mRNA_name)] %>%
inner_join(lncRNA_exp[,c("sample", lncRNA_name)], by = "sample")
# 使用 tryCatch 来处理可能的错误
cor_test = tryCatch({
cor.test(data[[mRNA_name]] %>% as.numeric(),
data[[lncRNA_name]] %>% as.numeric())
}, error = function(e) {
return(list(estimate = NA, p.value = NA)) # 当发生错误时返回NA
})
cor = cor_test$estimate
pvalue = cor_test$p.value
res = data.frame(mRNA = mRNA_name,
lncRNA = lncRNA_name,
Cor = cor,
Pvalue = pvalue)
res2 = res2 %>% bind_rows(res)
}
return(res2)
}