我正在做一个实验,其中有一些带有相关统计信息(实际上是许多其他统计信息和描述性列)的“区域”,以及这些区域中逗号分隔的基因列表。该列表的数量是可变的,并且可能不包含任何内容(“ NA”)。

我如何“融化”表:

  region_id  statistic      genelist
          1        2.5       A, B, C
          2        0.5    B, C, D, E
          3        3.2          <NA>
          4        0.1          E, F


为基因列表中的每个基因创建另一个带有单独条目的表?即

   region_id statistic gene
           1       2.5    A
           1       2.5    B
           1       2.5    C
           2       0.5    B
           2       0.5    C
           2       0.5    D
           2       0.5    E
           3       3.2 <NA>
           4       0.1    E
           4       0.1    F


我猜想有一种方法可以用R / plyr来做到这一点,但是我不确定怎么做。提前致谢。

编辑:

使用R,您可以使用以下代码重新创建这些玩具向量:

a <- structure(list(region_id = 1:4, statistic = c(2.5, 0.5, 3.2,
0.1), genelist = structure(c(1L, 2L, NA, 3L), .Label = c("A, B, C",
"B, C, D, E", "E, F"), class = "factor")), .Names = c("region_id",
"statistic", "genelist"), class = "data.frame", row.names = c(NA,
-4L))

b <- structure(list(region_id = c(1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L,
4L, 4L), statistic = c(2.5, 2.5, 2.5, 0.5, 0.5, 0.5, 0.5, 3.2,
0.1, 0.1), gene = structure(c(1L, 2L, 3L, 2L, 3L, 4L, 5L, NA,
5L, 6L), .Label = c("A", "B", "C", "D", "E", "F"), class = "factor")), .Names = c("region_id",
"statistic", "gene"), class = "data.frame", row.names = c(NA,
-10L))

最佳答案

有几种方法可以做到这一点。尽管可能有更好的方法,但这种方法可行...

library(stringr) # for str_split
join(subset(a, select=c("region_id", "statistic")),
     ddply(a, .(region_id), summarise, gene=str_split(genelist, ",\\S*")[[1]]))


需要plyr和stringer加载。

哦,这是一个更好的方法:

ddply(a, .(region_id),
      function(x) data.frame(gene=str_split(x$genelist, ",\\S*")[[1]],
                             statistic=x$statistic))

09-27 20:46