在R中实现100次重复矩阵Bootstrap及相关图构建问题解决
问题与解决:基于Bootstrap生成置换相关矩阵并构建图
数据集展示
library(igraph) vetor <- c(1, 5, 3, 8, 2, 9, 3, 2:15, 1, 5, 3, 6, 5, 9, 3 ) matrix(vetor, 7, 7) matrix <- matrix(vetor, 7, 7) matcor <- cor(matrix, method = "spearman") matrixnetwork = graph.adjacency(matcor, mode="undirected", weighted = TRUE, add.colnames=NULL, diag=FALSE) plot(matrixnetwork)
需求说明
目标是通过随机置换每个感兴趣区域(Region of Interest, ROI)内的值的顺序,生成100个Bootstrap相关矩阵,再基于每个矩阵构建图,用于后续t检验对比分析。
初始尝试与问题
使用boot包尝试实现:
Corr_fun = function(matrix, indices) { return(cor(matrix, method= "spearman")) } BIboot= boot(matrix, statistic= Corr_fun, R = 100) AIBOOT <- BIboot[["t"]]
该方法返回49×100的矩阵,运行以下代码时出现报错:Error in graph.adjacency.dense(adjmatrix, mode = mode, weighted = weighted, : not a square matrix.
g_boot <- graph_from_adjacency_matrix(AIBOOT, mode = "undirected", weighted = TRUE)
同时结果存在重复值问题。
其他尝试方法
使用bootstrap包
library(bootstrap) theta = function(matrix, indices) { return(as.matrix(matrix)) } # 用于中心性的函数 BOOTSAVE <- bootstrap(matrix, nboot = 100, theta)
返回结果不符合需求。
直接对图进行置换
尝试直接置换图结构,但仅能逐个操作,无法批量生成100次:
matrixnetwork2 <- permute(matrixnetwork, sample(vcount(matrixnetwork)))
可行解决方案
初始可行代码(未添加重复区域)
以数据集aibi_imuno_BI_1为例,最初尝试的可行代码:
N <- 7L set.seed(2023) R <- 100L BIboot <- vector("list", length = R) for(i in seq.int(R)) { indices <- sample(N, replace = TRUE) BIboot[[i]] <- cor(aibi_imuno_BI_1, method = "spearman") } g_boot_list <- lapply(BIboot, graph_from_adjacency_matrix, mode = "undirected", weighted = TRUE, add.colnames=NULL, diag=FALSE) plot(g_boot_list[[1]])
修正后代码
修正后实现了对ROI的随机置换,生成100个符合要求的相关矩阵:
# BOOT 1 N <- 7L set.seed(2023) R <- 100L BIboot <- vector("list", length = R) for(i in seq.int(R)) { indices <- sample(N, replace = TRUE) BIboot[[i]] <- cor(aibi_imuno_BI_1[indices, ], method = "spearman") } g_boot_list <- lapply(BIboot, graph_from_adjacency_matrix, mode = "undirected", weighted = TRUE, add.colnames=NULL, diag=FALSE) plot(g_boot_list[[1]])
此时已成功得到100个随机置换生成的Bootstrap相关矩阵,并能基于每个矩阵构建图,存储在列表g_boot_list中。
另外两种尝试方法
方法2:置换图结构
尝试批量置换图的节点顺序,但未关联原始数据的置换:
#############BOOTPERMUTATION FORMA 2 #################### N <- 7L set.seed(2023) R <- 100L BIPERMUT <- vector("list", length = R) for(i in seq.int(R)) { indices <- sample(N, replace = TRUE) BIPERMUT[[i]] <- permute(matrixnetwork, sample(vcount(matrixnetwork))) } plot(BIPERMUT[[1]]) degree(BIPERMUT[[1]], normalized = FALSE, loops = FALSE)
方法3:直接复制原始图
仅批量复制原始图,未进行任何置换操作:
#################FORMA 3 ####################### N <- 7L set.seed(2023) R <- 100L BIboot2 <- vector("list", length = R) for(i in seq.int(R)) { indices <- sample(N, replace = TRUE) BIboot2[[i]] <- matrixnetwork } plot(BIboot2[[1]]) degree(BIboot2[[1]], normalized = FALSE, loops = FALSE)
内容的提问来源于stack exchange,提问作者Ana Paula Castro
相关产品推荐
相关产品推荐

