【问题标题】:Building a Binary matrix out of a data frame after converting values of one column into rows in R在将一列的值转换为 R 中的行后,从数据框中构建二进制矩阵
【发布时间】:2021-04-21 14:56:52
【问题描述】:

我想从如下所示的数据框中构建一个二进制矩阵;两列,一列包含单元格类型,另一列包含标记。

Markers                                   Cell type                     
"CD3D, CD3E, CD3G, CD4"                   Peripheral blood_Normal_T helper cell
"CD3D, CD3E, CD3G, PTPRC"                 Peripheral blood_Normal_Memory T cell
"IL2RA, CD3D, CD3E, CD3G, CD4, FOXP3"     Peripheral blood_Normal_Regulatory T (Treg) cell
"CD3D, CD3E, CD3G, CD4, IFNG"             Peripheral blood_Normal_T helper1 (Th1) cell
"CD3D, CD3E, CD3G, CD4, IL4"              Peripheral blood_Normal_T helper2 (Th2) cell
"CD3D, CD3E, CD3G, CD4, IL17RA"           Peripheral blood_Normal_T helper17 (Th17) cell
"PROM1, PECAM1, CD34, PTPRC"              Peripheral blood_Gastric Cancer_Endothelial progenitor cell
"PROM1, PECAM1, CD34, PTPRC"              Peripheral blood_Gastric Cancer_Endothelial cell
CD14                                      Blood_Normal_Monocyte
NRP1                                      Blood_Normal_Plasmacytoid dendritic cell
GP1BA                                     Blood_Normal_T helper cell 

我希望最终输出采用以下结构。所以每个单元格类型都是自己的一列,每个标记有时是单个值,有时它们是几个标记,用逗号分隔为行。最后,如果标记存在于该特定细胞类型的标记列中,则每种细胞类型的矩阵值表示 1,否则为 0。

         Blood_Normal_T helper cell         Peripheral blood_Gastric Cancer_Endothelial progenitor cell
PROM1                 0                                              1
PECAM1                0                                              1
CD34                  0                                              1
PTPRC                 0                                              1
GP1BA                 1                                              0
.....

感谢您的帮助

【问题讨论】:

    标签: r dataframe matrix binary


    【解决方案1】:

    你可以这样做:

    library(tidyverse)
    df %>% 
       separate_rows(Markers) %>%
       xtabs(~., .)
    

    如果你只是使用基础 R:

    ind <- seq(nrow(df))
    
    table(merge(cbind(ind = ind, df[-1]),
                stack(setNames(strsplit(df$Markers, ","), ind)))[3:2])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-13
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2012-12-03
      • 2017-09-16
      • 2017-03-27
      相关资源
      最近更新 更多