Created
August 9, 2016 16:27
-
-
Save jnpaulson/405a65cc39a7b0236a0eefcc02a2555a to your computer and use it in GitHub Desktop.
function to merge two MRexperiments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extractMR<-function(obj){ | |
mat = MRcounts(obj) | |
ls = as.vector(libSize(obj)) | |
norm= as.vector(normFactors(obj)) | |
pd = pData(obj) | |
fd = fData(obj) | |
dat = list(counts=mat,librarySize=ls,normFactors=norm,pheno=pd,feat=fd) | |
return(dat) | |
} | |
mergeTable<-function(x,y){ | |
rows = union(rownames(x),rownames(y)) | |
cols = union(colnames(x),colnames(y)) | |
fullmat = array(NA,dim=c(length(rows),length(cols))) | |
rownames(fullmat) = rows | |
colnames(fullmat) = cols | |
fullmat[rownames(x),colnames(x)] = as.matrix(x) | |
fullmat[rownames(y),colnames(y)] = as.matrix(y) | |
fullmat | |
} | |
mergeMRexperiments<-function(x,y){ | |
xdat = extractMR(x) | |
ydat = extractMR(y) | |
xmat = xdat$counts; ymat = ydat$counts | |
cnames = union(colnames(xmat),colnames(ymat)) | |
if(length(cnames)!=(ncol(x)+ncol(y))){ | |
message("MRexperiment 1 and 2 share sample ids; adding labels to sample ids.") | |
newXnames = paste(colnames(xmat),"x",sep=".") | |
newYnames = paste(colnames(ymat),"y",sep=".") | |
cnames = union(newXnames,newYnames) | |
colnames(xdat$counts) = | |
rownames(xdat$pheno) = | |
names(xdat$normFactors) = | |
names(xdat$librarySize) = | |
newXnames | |
colnames(ydat$counts) = | |
rownames(ydat$pheno) = | |
names(ydat$normFactors) = | |
names(ydat$librarySize) = | |
newYnames | |
} | |
print("counts") | |
counts = mergeTable(xdat$counts,ydat$counts) | |
print("pheno") | |
pheno = as.data.frame(mergeTable(xdat$pheno,ydat$pheno)) | |
print("feat") | |
feat = as.data.frame(mergeTable(xdat$feat,ydat$feat)) | |
librarySize = c(xdat$librarySize,ydat$librarySize) | |
normFactors = c(xdat$normFactors,ydat$normFactors) | |
if(any(is.na(counts))){ | |
message("There were OTUs not shared between objects. Coercing values to 0.") | |
counts[is.na(counts)] = 0 | |
} | |
obj = newMRexperiment(counts=counts, | |
normFactors=normFactors, | |
libSize=librarySize, | |
phenoData = AnnotatedDataFrame(pheno), | |
featureData=AnnotatedDataFrame(feat)) | |
return(obj) | |
} | |
# test the function | |
# phenotype info is transformed from numeric into character | |
library(metagenomeSeq) | |
data(mouseData) | |
newobj = mergeMRexperiments(mouseData,mouseData) | |
newobj | |
# will eventually add options to merge rows by keys instead of rownames | |
data(lungData) | |
newobj = mergeMRexperiments(mouseData,lungData) | |
newobj |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment