R中循环处理多组间相关性分析

2023-11-30 14:35:22 浏览数 (1)

加载R包

代码语言:javascript复制
library(tidyverse)
library(readxl)
library(psych)
library(reshape2)
library(magrittr)

导入数据

代码语言:javascript复制
df1 <- read_excel("env.xlsx") %>% 
  mutate(group=ID) %>% 
  mutate(group = str_replace_all(group, "[0-9]", "")) %>% 
  select(-ID) %>% 
  group_by(group) %>% 
  nest()

df2 <- read_excel("SOC.xlsx") %>% 
  mutate(group=ID) %>% 
  mutate(group = str_replace_all(group, "[0-9]", "")) %>%
  select(-ID) %>% 
  group_by(group) %>% 
  nest()

循环整合数据

代码语言:javascript复制
# 初始化一个空的数据框来存储结果
results_df <- data.frame(group = character(),
                         cor = numeric(),
                         pvalue = numeric(),
                         stringsAsFactors = FALSE)

# 循环处理每一对数据集
for (i in 1:5) {
  pp <- corr.test(df1$data[[i]], df2$data[[i]], method = "pearson", adjust = "fdr")
  results_df <- rbind(results_df, data.frame(
    group = paste0("cor", i),
    cor = pp$r,
    pvalue = pp$p,
    stringsAsFactors = FALSE
  ))
}

数据可视化

代码语言:javascript复制
results_df %>% set_colnames(c("group","rvalue","pvalue")) %>% 
  rownames_to_column(var="env") %>% 
  mutate(env = str_replace_all(env, "[0-9]", "")) %>%
  mutate(p_signif=symnum(pvalue, corr = FALSE, na = FALSE,  
                         cutpoints = c(0, 0.001, 0.01, 0.05, 0.1, 1), 
                         symbols = c("***", "**", "*", "", " "))) %>% 
  
  ggplot(aes(group,env,fill=rvalue)) 
  geom_tile() 
  geom_text(aes(label=p_signif),
            size=6,color="white",hjust=0.5,vjust=0.5) 
  labs(x=NULL,y=NULL) 
  scale_color_gradientn(colours = rev(RColorBrewer::brewer.pal(3,"RdBu"))) 
  scale_fill_gradientn(colours = rev(RColorBrewer::brewer.pal(3,"RdBu"))) 
  scale_y_discrete(expand=c(0,0)) 
  scale_x_discrete(expand=c(0,0))  
  theme(axis.text.x=element_text(angle =0,hjust =1,vjust =0.5,
                                 color="black",size = 8),
        axis.text.y=element_text(color="black",size =8),
        axis.ticks= element_blank(),
        panel.spacing.y = unit(0,"cm"),
        plot.background = element_blank(),
        panel.background = element_blank(),
        legend.title = element_blank()) 
  scale_size(range=c(1,10),guide=NULL) 
  guides(fill=guide_colorbar(direction="vertical",reverse=F,barwidth=unit(.5,"cm"),
                             barheight=unit(8,"cm")))

0 人点赞