I used following code to create correlation matrix and generate pvalue. How do I create adjusted pvalue for each correlation?
library(corrplot)
#Running correlation
M = cor(mtcars)
#identifying pvalues
testRes = cor.mtest(mtcars, conf.level = 0.95)
#creating pairwise p value
pval = as.data.frame(as.table(testRes$p))
head(pval)
output is:
Var1 Var2 Freq
<fct> <fct> <dbl>
1 mpg mpg 0.000000e+00
2 cyl mpg 6.112687e-10
3 disp mpg 9.380327e-10
4 hp mpg 1.787835e-07
5 drat mpg 1.776240e-05
6 wt mpg 1.293959e-10
How do I calculate adjusted pvalue here and add it in the colimn after pvalue?
Actually it's just cbind(<res>, p.adj=p.adjust(<res>$p, method='BH'))
.
First the correlation p-values solution without using the corrplot package.
pm <- outer(mtcars, mtcars, Vectorize(\(x, y) cor.test(x, y)$p.value))
res <- as.data.frame(as.table(pm)) |> setNames(c("Var1", "Var2", "p"))
Now, cbind
adj. p-values; I use the Benjamini-Hochberg aka false discovery rate (FDR) method. Also common is the "bonferroni"
method; see ?p.adjust
for options.
res <- cbind(res, p.adj=p.adjust(res$p, method='BH')) ## here you could use any `res`, e.g. your `pval` object and `pval&Freq`
head(res)
# Var1 Var2 p p.adj
# 1 mpg mpg 0.000000e+00 0.000000e+00
# 2 cyl mpg 6.112687e-10 3.892817e-09
# 3 disp mpg 9.380327e-10 5.404855e-09
# 4 hp mpg 1.787835e-07 6.555396e-07
# 5 drat mpg 1.776240e-05 3.770615e-05
# 6 wt mpg 1.293959e-10 9.209941e-10
If you like pipes, you can do:
res <- outer(mtcars, mtcars, Vectorize(\(x, y) cor.test(x, y)$p.value)) |>
as.table() |> as.data.frame() |> setNames(c("Var1", "Var2", "p")) |>
{\(.) cbind(., p.adj=p.adjust(.$p, method='BH'))}()
head(res)
# Var1 Var2 p p.adj
# 1 mpg mpg 0.000000e+00 0.000000e+00
# 2 cyl mpg 6.112687e-10 3.892817e-09
# 3 disp mpg 9.380327e-10 5.404855e-09
# 4 hp mpg 1.787835e-07 6.555396e-07
# 5 drat mpg 1.776240e-05 3.770615e-05
# 6 wt mpg 1.293959e-10 9.209941e-10