how to combine two files into one in R and filtering

Hi all,

I do have a correlation matrix and p-value file. Could you please help how I can add p-value into the correlation file and then how to filter significant correlation based on p-value and strong correlation based on correlation value?

cor <- read.table("r.correlation.txt", sep="\t", header=T, blank.lines.skip=F, check.names=F)
head(cor)
Var1 Var2 value
1 1 G1 G1 1
2 2 G2 G1 0.312280701754386
3 3 G3 G1 0.0157894736842105
4 4 G4 G1 -0.101754385964912
5 5 G5 G1 0.0964912280701754
6 6 G6 G1 -0.40477173313538
P <- read.table("pvalues.txt", sep="\t", header=T, blank.lines.skip=F, check.names=F)
head(P)
Var1 Var2 value
1 1 G1 G1 NA
2 2 G2 G1 0.193042467797002
3 3 G3 G1 0.948846126455514
4 4 G4 G1 0.678504619638732
5 5 G5 G1 0.694348438958584
6 6 G6 G1 0.0856060025429972

a better way to share your example data:

library(tidyverse)
cor <- tibble::tribble(
  ~Var1, ~Var2,             ~value,
  "G1",  "G1",                  1,
  "G2",  "G1",  0.312280701754386,
  "G3",  "G1", 0.0157894736842105,
  "G4",  "G1", -0.101754385964912,
  "G5",  "G1", 0.0964912280701754,
  "G6",  "G1",  -0.40477173313538
)

tibble::tribble(
  ~Var1, ~Var2,             ~value,
  "G1",  "G1",                 NA,
  "G2",  "G1",  0.193042467797002,
  "G3",  "G1",  0.948846126455514,
  "G4",  "G1",  0.678504619638732,
  "G5",  "G1",  0.694348438958584,
  "G6",  "G1", 0.0856060025429972
)

example solution


(together <- bind_cols(cor,select(P,pval=value)))

together %>%
  filter(
    pval<.3,
    abs(value)>.4
  )

Thank you so much @nirgrahamuk . I was able to combine the files but the filtering command is not working.

I am using below code;



cor_5 <- rcorr(as.matrix(M),type=c("spearman"))

r_mat <- cor_5$r
p_mat <- cor_5$P
r_mat_long <- melt(r_mat)
p_mat_long<- melt(p_mat)

colnames(r_mat_long)[which(names(r_mat_long) == "value")] <- "correlation"
colnames(p_mat_long)[which(names(p_mat_long) == "value")] <- "pVal"

(together <- bind_cols(r_mat_long,select(p_mat_long,pVal)))

together %>%
  filter(
    pVal<.01,
    abs(correlation)>.4
  )

write.table(together, "r.p.correlation.txt")

before you write.table you would need to capture the result of the filter operation, rather than just letting it print as I had.

t2 <- together %>%
  filter(
    pVal<.01,
    abs(correlation)>.4
  )

write.table(t2, "r.p.correlation.txt")

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.