如何将嵌套dataframe组成的列表转换为基于共有值的计数矩阵
R实现方案
方法1:基础R实现(无需安装额外包)
# 获取所有分组名和去重后的全部基因名 all_groups <- names(list1) all_genes <- unique(unlist(lapply(list1, function(x) x[[1]]))) # 初始化行列名匹配的全0计数矩阵 count_matrix <- matrix( 0, nrow = length(all_groups), ncol = length(all_genes), dimnames = list(all_groups, all_genes) ) # 遍历分组,将存在的基因对应位置赋值为1 for (group_name in all_groups) { target_genes <- list1[[group_name]][[1]] count_matrix[group_name, target_genes] <- 1 }
方法2:tidyverse风格实现
library(tidyverse) all_groups <- names(list1) all_genes <- unique(unlist(lapply(list1, function(x) x[[1]]))) count_matrix <- imap_dfr(list1, ~ tibble(group = .y, gene = .x[[1]])) %>% # 标记存在的基因为1 mutate(value = 1) %>% # 补全所有分组和基因的组合,缺失值填0 complete(group = all_groups, gene = all_genes, fill = list(value = 0)) %>% # 转为宽表 pivot_wider(names_from = gene, values_from = value) %>% # 分组名设为行名,转为矩阵格式 column_to_rownames("group") %>% as.matrix()
运行上述任意一种代码得到的count_matrix即为你需要的计数矩阵,包含空分组METCC的全0行。如果需要基因列按字母排序,只需要在获取all_genes时加一步排序:
all_genes <- sort(unique(unlist(lapply(list1, function(x) x[[1]]))))
内容的提问来源于stack exchange,提问作者Krutik
相关产品推荐
相关产品推荐

