a <- ifelse(as.matrix(pvalue2) < .05, as.matrix(pvalue2), "normal")
a <- as.data.frame(a)
由于 R 是一种未经编译的高级语言,因此for
循环在增长时往往会变得非常缓慢。通过使用矢量化函数(在内部以较低级别的语言进行循环),您可以加快代码速度并使其更具可读性。
示例运行
> set.seed(123)
> pvalue2 <- matrix(runif(18)/10, 6, 3)
> pvalue2[sample(length(pvalue2), 4)] <- NA
> pvalue2 <- as.data.frame(pvalue2)
> pvalue2
V1 V2 V3
1 0.02875775 0.05281055 0.067757064
2 0.07883051 0.08924190 0.057263340
3 0.04089769 0.05514350 NA
4 0.08830174 0.04566147 0.089982497
5 0.09404673 NA NA
6 NA 0.04533342 0.004205953
> ifelse(as.matrix(pvalue2) < .05, as.matrix(pvalue2), "normal")
V1 V2 V3
[1,] "0.0287577520124614" "normal" "normal"
[2,] "normal" "normal" "normal"
[3,] "0.04089769218117" "normal" NA
[4,] "normal" "0.0456614735303447" "normal"
[5,] "normal" NA NA
[6,] NA "0.0453334156190977" "0.00420595335308462"