如何将 pairwise comaprison 重塑为矩阵并在 R 中创建相关热图?

How to reshape a pairwise comaprison into matrix and create a correlation heatmap in R?

我希望有人能帮助我。

我有这个数据框,它是 dunnTest() 的输出,其中包含成对比较和 p 值。 dunnTest() 的示例输出如下。我想要做的是将数据框重塑为矩阵并创建热图图或相关图块以可视化哪些组彼此之间存在显着差异。输出应该类似于下图。但是,图块内的数据不是相关值,而是来自 dunnTest()

的 p 值

我试图解决的问题与此link中发布的问题类似,但是没有给出答案。希望这次有人能回答这样的问题。

我尝试了 data.matrix(),但它没有根据“比较”列正确转换数据。

sorted <- 
    tibble::tribble(
      ~Comparison, ~Z, ~P.adj,
      "A1 - B1",    0.225445,     0.854086,
      "A1 - B2",    0.45513,     0.000235,
      "A1- B3",    0.32555,     0.221551,
       "B1 - B2",   0.44544,       0.0000552,
       "B2 - B3",    0.22511,      0.0000112)

如果我理解正确的话,这可能会对你有所帮助

图书馆

library(tidyverse)

数据

sorted <- 
  tibble::tribble(
    ~Comparison, ~Z, ~P.adj,
    "A1 - B1",    0.225445,     0.854086,
    "A1 - B2",    0.45513,     0.000235,
    "A1- B3",    0.32555,     0.221551,
    "B1 - B2",   0.44544,       0.0000552,
    "B2 - B3",    0.22511,      0.0000112)

x <- c("A1","B1","B2","B3")

代码

sorted %>% 
  #Separate variable Comparison in two columns
  separate(col = Comparison,into = c("var1","var2")) %>% 
  #Create temporary data.frame 
  {. ->> temp} %>% 
  #Stack temporary data.frame so we have both A1-B1 and B1-A1
  bind_rows(
    temp %>%
      rename(var1 = var2,var2 = var1)
  ) %>% 
  #Join with a combination of all levels to make a "complete matrix"
  full_join(
    expand_grid(var1 = x,var2 = x)
  ) %>% 
  mutate(
    #Rounding p-value
    P.adj = round(P.adj,4),
    #Creating a variable just for the text inside the tile, with a condition
    p_lbl = if_else(P.adj < 0.05,paste0(P.adj,"*"),as.character(P.adj))) %>% 
  #Using variable P.adj as colour 
  ggplot(aes(x = var1,y = var2,fill = P.adj))+
  geom_tile(col = "black")+
  #Optional pallette 
  scale_fill_viridis_c()+
  # Add p-values as text inside the tiles
  geom_text(aes(label = p_lbl), fontface = "bold",size = 5)

情节