I’m doing an experiment where I have “regions” with some associated statistic (actually many other statistics and descriptive columns), and a comma-separated list of genes that lie in those regions. This list will be variable in number, and may not contain anything (“NA”).
How can I “melt” table a:
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
To create another table with a separate entry for each gene in the list of genes? I.e.
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
I’m guessing there’s a way to do this with R/plyr, but I’m not sure how. Thanks in advance.
Edit:
Using R you can recreate these toy vectors with this code:
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))
There are a few ways to do it. This way works, although there may be better ways…
Needs plyr and stringr loaded.
Oh, here’s a better way: