Question

I'm working with a large matrix, M, which contains sample by gene data. Certain elements contain multiple concatenated entries, but the vectors have been converted to characters:

        geneA    gene2             
sample1    NA    NA                
sample2    "c(\"siteX\", \"siteY\")"    "0"
sample3    "siteZ"    "0"

So when I call unique(M[,'geneA']) I get:

NA    "c(\"siteX\", \"siteY\")"    "siteZ"

Is there any way to 'de-characterize' the matrix so that I can obtain all of the unique values for geneA when I run my code? Or would it be better to focus instead on extracting and manipulating the elements of interest using regular expressions?

Thanks in advance!

edit:

> dput(tmp)
structure(c(NA, "c(\"siteX\", \"siteY\")", 
"siteZ", NA, "0", "0"), .Dim = c(3L, 2L), .Dimnames = list(
c("sample1", "sample2", "sample3"), c("geneA", 
"gene2")))
Was it helpful?

Solution

If you just want the unique geneA values:

df = structure(c(NA, "c(\"siteX\", \"siteY\")", "siteZ", NA, "0", "0"), .Dim = c(3L, 2L), 
               .Dimnames = list(c("sample1", "sample2", "sample3"), c("geneA", "gene2")))
df = data.frame(df,stringsAsFactors=F)
df$geneA = as.character(df$geneA)
geneA = unlist(sapply(df$geneA, 
                      function(x) 
                      { sapply(strsplit(x,",")[[1]], 
                               function(x) { sub(".*\"(\\w+)\".*", "\\1", x,perl=TRUE) }      )  }))
names(geneA) = NULL
unique(geneA)

Nicer ordering and cleaning into a data frame with removal of NA geneA's:

df = structure(c(NA, "c(\"siteX\", \"siteY\")", "siteZ", NA, "g1", "g2"), .Dim = c(3L, 2L), 
               .Dimnames = list(c("sample1", "sample2", "sample3"), c("geneA", "gene2")))
df = data.frame(df,stringsAsFactors=F)
df$geneA = as.character(df$geneA)
require(plyr)
ddply(df, "geneA", function(x)
    { 
      if(!is.na(x))
      {
        geneAs = sapply(strsplit(x$geneA,",")[[1]], function(y) { sub(".*\"(\\w+)\".*", "\\1", y,perl=TRUE) } );
        return(data.frame("geneA"= geneAs, "gene2" = rep(x$gene2[1],length(geneAs)) )) 
      } else return(NULL)
    } )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top