R/io.R

Defines functions read.metfile write.metfile

Documented in read.metfile write.metfile

#' @title Read metabolomics data
#' @description \code{read.metfile} read in a standard metabolomics dataset in csv format.
#' The input table can be partitioned into 4 rectangular region.
#' The top left is blank. The top right is row headers. The down left is column headers.
#' The down right is metabolites signal matrix, whose columns are samples in injection order and rows are metabolites.
#' @param file Name of cvs file of the metabolomics dataset.
#' @param nrowheader Number of row headers in the file. Default is 4.
#' @param ncolheader Number of column headers in the file. Default is 7.
#' @param metcol Column index of the metabolites ID. Default is 1.
#' @param smplrow Row index of the sample ID. Default is 4.
#' @param resmpl Regular expression of the sample IDs to be analyzed (which is used in \code{grepl}). Default includes all the samples.
#' @return A data frame of metabolites signal. Each row is a metabolite and each column is a sample.
#' @author Liu Cao
#' @export

read.metfile <- function(filename, nrowheader=4, ncolheader=7, metcol=1, smplrow=4, resmpl=""){
  dfraw = read.csv(filename, header=FALSE, as.is=TRUE)
  nrow = dim(dfraw)[1]
  ncol = dim(dfraw)[2]

  metdata = dfraw[(nrowheader+1):nrow,(ncolheader+1):ncol]
  metID = dfraw[(nrowheader+1):nrow,metcol]
  sampleID = dfraw[smplrow,(ncolheader+1):ncol]

  rownames(metdata) = metID
  colnames(metdata) = sampleID

  sampleIndex = grepl(resmpl,sampleID)
  metdata = metdata[,sampleIndex]
  print(paste0(dim(metdata)[2]," samples are selected."))
  print(paste0(dim(metdata)[1]," metabolites will be analyzed."))

  return(metdata)
}

#' @title Write metabolomics data
#' @description \code{write.metfile} output csv file of false or good metabolites signal according to type I criterion or type II criterion.
#' @param data Data frame generated by \code{\link{read.metfile}}
#' @param falsig The list generated by \code{\link{falsignal}}
#' @param type type=1 outputs type I false signal. type=2 outputs type II false signal. Default is 1.
#' @param trans whether to transponse the table. Default is TRUE, or with rows of samples and columns of metabolites.
#' @return None
#' @author Liu Cao
#' @export

write.metfile <- function(data,falsig,type="1", trans=TRUE){
  boolbad = NULL
  if(type == "1"){
    boolbad = falsig$boolbad1
  }
  else{
    boolbad = falsig$boolbad2
  }
  datagood = data[!boolbad,]
  databad = data[boolbad,]

  if(trans){
    datagood = t(datagood)
    databad = t(databad)
  }
  write.csv(datagood,file=paste0("type",type,"_","good.csv"),quote=FALSE)
  write.csv(databad,file=paste0("type",type,"_","bad.csv"),quote=FALSE)
}
liucaomics/genuMet documentation built on Nov. 11, 2019, 12:13 a.m.