diff --git a/R/comparisonMatrix.R b/R/comparisonMatrix.R index 0b07d09..88cde65 100644 --- a/R/comparisonMatrix.R +++ b/R/comparisonMatrix.R @@ -1,7 +1,7 @@ #' Create a matrix of which pairwise comparisons to make -#' +#' #' Construct a matrix of pairwise comparisons (pairs can be either samples or groups) -#' +#' #' @param ftmsObj ftmsData object #' @param comparisons dictates which pairwise comparisons to make. 'all' will create a matrix for all pairwise comparisons, 'control' will create a matrix for all comparisons against a specified control group, 'one-factor' will create a matrix of pairwise comparisons to be made where only one 'main_effect' changes between the two groups, or a list of specific comparisons to be made (e.g., list(c("Group1","Group2"),c("Group3","Group4"))) can be given. #' @param control if wanting to only compare against a control, must specify which group or sample is the control @@ -10,29 +10,32 @@ comparisonMatrix <- function(ftmsObj, comparisons, control=NULL) { if (missing(ftmsObj)) stop("ftmsObj is missing") if (missing(comparisons)) stop("comparisons is missing") if (!inherits(ftmsObj, "ftmsData")) stop("ftmsObj must be of type ftmsData") - + groupDF <- attr(ftmsObj, "group_DF") + if (is.null(groupDF)) { ## this means each sample is its own group so construct a dummy groupDF - + if(all(tolower(comparisons) == "one-factor")){ stop("The 'one-factor' specification cannot be used without a group data frame. Please use 'group_designation' first.") } - + samp.names <- unique(ftmsObj$f_data[, getFDataColName(ftmsObj)]) groupDF <- data.frame(Sample=samp.names, Group=samp.names) colnames(groupDF)[1] <- getFDataColName(ftmsObj) + } else { + if(is.factor(groupDF$Group)){groupDF$Group <- droplevels(groupDF$Group)} } - + if (!missing(control) & !is.null(control)) { if (!(control %in% groupDF$Group)) { stop(paste0("control column '", control, "' not found in the data")) } } - + # determine which pairwise comparisons to make if(is.list(comparisons)){ if (!all(unlist(comparisons) %in% groupDF$Group)) { stop("not all groups specified in pairs parameter were found in the data") } - + pairs <- do.call(cbind, comparisons) } else if(tolower(comparisons) == "all"){ pairs <- combn(levels(as.factor(groupDF$Group)),2) @@ -52,25 +55,25 @@ comparisonMatrix <- function(ftmsObj, comparisons, control=NULL) { }else{ stop("check that comparisons argument is either 'all', 'control', 'one-factor', or a list of specific comparisons") } - + return(pairs) - + } #' Create a list of which pairwise comparisons to make -#' +#' #' Construct a list of pairwise comparisons, where only #' one main effect changes between each group -#' +#' #' @param ftmsObj ftmsData object #' @param groupDF group data frame from ftmsData object #' @return a list of which pairwise comparisons to make one_factor_change <- function(ftmsObj, groupDF){ - + # Get only uniuqe groups df <- groupDF[!duplicated(groupDF$Group),] - + # Remove Sample and Group columns if(ncol(df) > 2){ df <- df[,-which(colnames(df) %in% c(getFDataColName(ftmsObj), "Group"))] @@ -78,36 +81,36 @@ one_factor_change <- function(ftmsObj, groupDF){ df <- as.data.frame(df[,-which(colnames(df) %in% getFDataColName(ftmsObj))]) colnames(df) <- "Group" } - + # Make sure it's character, not factor df <- apply(df, 2, as.character) - + # Compare each row to every other row res <- lapply(c(1:(nrow(df)-1)), function(i){ - + res <- lapply(c((i+1):nrow(df)), function(j){ - + temp <- apply(as.data.frame(df[c(i,j),]), 2, function(k){ - + k[1] == k[2] - + }) - - data.frame(Grp1=paste(df[i,], collapse="_"), - Grp2=paste(df[j,], collapse="_"), + + data.frame(Grp1=paste(df[i,], collapse="_"), + Grp2=paste(df[j,], collapse="_"), Compare = (sum(temp) == (ncol(df)-1))) - + }) - + return(do.call(rbind, res)) - + }) - + res <- do.call(rbind, res) fin <- subset(res, Compare) - + ret <- lapply(c(1:nrow(fin)), function(x) c(as.character(fin$Grp1)[x], as.character(fin$Grp2)[x])) - + return(ret) - -} \ No newline at end of file + +} diff --git a/R/mapCompoundsToModules.R b/R/mapCompoundsToModules.R index 147e3f5..6522d79 100644 --- a/R/mapCompoundsToModules.R +++ b/R/mapCompoundsToModules.R @@ -1,13 +1,13 @@ #' Map compound level data to modules in MetaCyc -#' +#' #' Map compound data to MetaCyc modules The database used #' is determined by the database previously used to map peaks to compounds. #' For MetaCyc, modules are pathways that are not super-pathways #' @param compoundObj an object of type compoundData #' @return moduleData object -#' +#' #' @author Amanda White -#' +#' #' @export mapCompoundsToModules <- function(compoundObj) { if (!inherits(compoundObj, "compoundData")) { @@ -25,17 +25,17 @@ mapCompoundsToModules <- function(compoundObj) { compounds <- mc_compounds data("mc_compound_reaction_map") comp_rxn_map <- mc_compound_reaction_map - + # mapping from compound --> reaction --> module node data("mc_reaction_module_node_map") reaction_module_node_map <- mc_reaction_module_node_map - + } if (getDataScale(compoundObj) != "pres") { compoundObj <- edata_transform(compoundObj, data_scale="pres") } - + comp_rxn <- comp_rxn_map ind <- unlist(lapply(comp_rxn, function(x) return(all(is.null(x)) || all(is.na(x))))) comp_rxn <- comp_rxn[!ind] @@ -47,44 +47,47 @@ mapCompoundsToModules <- function(compoundObj) { comp_rxn_mod <- dplyr::inner_join(comp_rxn, reaction_module_node_map, by=c('Reaction'='REACTION')) comp_rxn_mod <- dplyr::rename(comp_rxn_mod, Module = MODULE, Module_Node = MODULE_NODE) %>% dplyr::mutate(Module_Node_Comb=paste0(Module, ": ", Module_Node)) - - # add compounds to e_data - e_data <- dplyr::select_(compoundObj$e_meta, getCompoundColName(compoundObj), getEDataColName(compoundObj)) %>% + + # add compounds to e_data + e_data <- compoundObj$e_meta %>% + dplyr::select(dplyr::all_of(c( + getCompoundColName(compoundObj), + getEDataColName(compoundObj) + ))) %>% dplyr::left_join(compoundObj$e_data, by=getEDataColName(compoundObj)) %>% dplyr::select(-dplyr::matches(getEDataColName(compoundObj))) - + # join e_data to compound/reaction/module mapping join_by <- c("Compound") names(join_by) <- getCompoundColName(compoundObj) - e_data <- dplyr::inner_join(comp_rxn_mod, e_data, by=join_by) - + e_data <- dplyr::inner_join(comp_rxn_mod, e_data, by=join_by) + # get compounds observed in this dataset for each reaction (for e_meta) - observed_comp_per_rxn <- e_data %>% - dplyr::mutate(n_samples_848234=rowSums(dplyr::select(., -dplyr::one_of(c(getCompoundColName(compoundObj)), "Reaction", "Module_Node", "Module", "Module_Node_Comb")))) %>% - dplyr::select_(getCompoundColName(compoundObj), "Module_Node_Comb", "n_samples_848234") %>% + observed_comp_per_rxn <- e_data %>% + dplyr::mutate(n_samples_848234 = rowSums(dplyr::select(.,-dplyr::any_of(c(getCompoundColName(compoundObj),"Reaction", "Module_Node", "Module", "Module_Node_Comb"))))) %>% + dplyr::select(dplyr::all_of(c(getCompoundColName(compoundObj), "Module_Node_Comb", "n_samples_848234"))) %>% dplyr::filter(n_samples_848234 > 0) %>% dplyr::select(-n_samples_848234) %>% dplyr::group_by(Module_Node_Comb) %>% - dplyr::rename_(Compound = getCompoundColName(compoundObj)) %>% + dplyr::rename(Compound = getCompoundColName(compoundObj)) %>% dplyr::summarise(Compounds_in_Dataset=paste(Compound, collapse=";")) - + e_meta <- dplyr::select(e_data, Module_Node, Module, Module_Node_Comb) %>% dplyr::left_join(observed_comp_per_rxn, by="Module_Node_Comb") - + ## Calculate number of UNIQUE compounds per node e_data <- e_data %>% - dplyr::group_by_("Module_Node_Comb", getCompoundColName(compoundObj)) %>% - dplyr::summarise_if(is.numeric, dplyr::funs(sum)) %>% - dplyr::ungroup() - + dplyr::group_by(dplyr::across(dplyr::all_of(c("Module_Node_Comb",getCompoundColName(compoundObj))))) %>% + dplyr::summarise(dplyr::across(dplyr::where(is.numeric), sum),.groups = "drop") + e_data <- e_data %>% dplyr::mutate_if(is.numeric, dplyr::funs(ifelse(.>0, 1, 0))) %>% dplyr::select(-dplyr::matches(getCompoundColName(compoundObj))) %>% dplyr::group_by(Module_Node_Comb) %>% - dplyr::summarise_all(dplyr::funs(sum)) %>% + dplyr::summarise_all(dplyr::funs(sum)) %>% dplyr::ungroup() %>% as.data.frame() - + # get # OBSERVABLE compounds per reaction subject to mass filter applied to compoundObj obs_comp <- dplyr::inner_join(comp_rxn_mod, compounds, by=c('Compound'='COMPOUND')) if (!is.null(attr(compoundObj, "filters")) && !is.null(attr(compoundObj, "filters")$massFilt)) { @@ -96,15 +99,15 @@ mapCompoundsToModules <- function(compoundObj) { stop(paste("Unknown database:", db)) } } - + obs_comp <- dplyr::group_by(obs_comp, Module_Node_Comb) %>% dplyr::summarise(`N_Observable_Compounds`=dplyr::n_distinct(Compound)) e_meta <- dplyr::left_join(e_meta, obs_comp, by="Module_Node_Comb") %>% as.data.frame() e_meta <- dplyr::arrange(e_meta, Module, Module_Node_Comb) - - result <- as.moduleData(e_data, compoundObj$f_data, e_meta, edata_cname = "Module_Node_Comb", - fdata_cname=getFDataColName(compoundObj), module_cname="Module", - module_node_cname = "Module_Node", instrument_type = getInstrumentType(compoundObj), + + result <- as.moduleData(e_data, compoundObj$f_data, e_meta, edata_cname = "Module_Node_Comb", + fdata_cname=getFDataColName(compoundObj), module_cname="Module", + module_node_cname = "Module_Node", instrument_type = getInstrumentType(compoundObj), db=getDatabase(compoundObj)) #attributes from compoundData to carry forward: @@ -113,7 +116,7 @@ mapCompoundsToModules <- function(compoundObj) { # result <- ftmsRanalysis:::setInstrumentType(result, getInstrumentType(compoundData)) result <- ftmsRanalysis:::setDataScale(result, "count") attr(result, "filters") <- attr(compoundObj, "filters") - + ## TODO: are there any other cnames that need to be carried through?? if (!is.null(attr(compoundObj, "cnames")$extraction_cname)) { attr(result, "cnames")$extaction_cname <- attr(compoundObj, "cnames")$extraction_cname diff --git a/R/mapCompoundsToReactions.R b/R/mapCompoundsToReactions.R index 83dc010..9fd5128 100644 --- a/R/mapCompoundsToReactions.R +++ b/R/mapCompoundsToReactions.R @@ -1,11 +1,11 @@ #' Map compound level data to reactions in MetaCyc -#' -#' Map compound data to MetaCyc reactions. +#' +#' Map compound data to MetaCyc reactions. #' @param compoundObj an object of type compoundData #' @return reactionData object -#' +#' #' @author Amanda White -#' +#' #' @export mapCompoundsToReactions <- function(compoundObj) { if (!inherits(compoundObj, "compoundData")) { @@ -14,20 +14,20 @@ mapCompoundsToReactions <- function(compoundObj) { if (anyDuplicated(compoundObj$e_data[, getEDataColName(compoundObj)]) > 0) { stop("compoundObj$e_data cannot have duplicates in the getEDataColName(compoundObj) column") } - + db <- getDatabase(compoundObj) if (toupper(db) == "METACYC") { require(MetaCycData) data("mc_reactions") reactions <- mc_reactions %>% dplyr::rename(ENZYME=`EC-NUMBER`) - + data("mc_compounds") - compounds <- mc_compounds + compounds <- mc_compounds data("mc_compound_reaction_map") comp_rxn_map <- mc_compound_reaction_map } - + if (getDataScale(compoundObj) != "pres") { compoundObj <- edata_transform(compoundObj, data_scale="pres") } @@ -39,71 +39,79 @@ mapCompoundsToReactions <- function(compoundObj) { comp_rxn <- tibble::tibble(Compound=names(comp_rxn), Reaction=comp_rxn) %>% tidyr::unnest() %>% dplyr::filter(!is.na(Reaction)) - - # add compounds to e_data - e_data <- dplyr::select_(compoundObj$e_meta, getCompoundColName(compoundObj), getEDataColName(compoundObj)) %>% - dplyr::left_join(compoundObj$e_data, by=getEDataColName(compoundObj)) %>% + + # add compounds to e_data + e_data <- compoundObj$e_meta %>% + dplyr::select(dplyr::all_of(c( + getCompoundColName(compoundObj), + getEDataColName(compoundObj) + ))) %>% + dplyr::left_join( + compoundObj$e_data, + by = getEDataColName(compoundObj) + ) %>% dplyr::select(-dplyr::matches(getEDataColName(compoundObj))) - + # join e_data to reactions table by compound column join_by <- c("Compound") names(join_by) <- getCompoundColName(compoundObj) e_data <- dplyr::inner_join(comp_rxn, e_data, by=join_by) - + # get compounds observed in this dataset for each reaction (for e_meta) - observed_comp_per_rxn <- e_data %>% dplyr::mutate(n_samples_848234=rowSums(dplyr::select(., -dplyr::one_of(c(getCompoundColName(compoundObj), "Reaction"))))) %>% - dplyr::select_(getCompoundColName(compoundObj), "Reaction", "n_samples_848234") %>% + observed_comp_per_rxn <- e_data %>% + dplyr::mutate(n_samples_848234 = rowSums(dplyr::select(.,-dplyr::any_of(c(getCompoundColName(compoundObj), "Reaction"))))) %>% + dplyr::select(dplyr::all_of(c(getCompoundColName(compoundObj), "Reaction", "n_samples_848234"))) %>% dplyr::filter(n_samples_848234 > 0) %>% dplyr::select(-n_samples_848234) %>% dplyr::group_by(Reaction) %>% - dplyr::rename_(Compound = getCompoundColName(compoundObj)) %>% + dplyr::rename(Compound = getCompoundColName(compoundObj)) %>% dplyr::summarise(Compounds_in_Dataset=paste(Compound, collapse=";")) - + # collapse Reaction rows in e_data - e_data <- e_data %>% + e_data <- e_data %>% dplyr::group_by(Reaction) %>% dplyr::select(-dplyr::matches(getCompoundColName(compoundObj))) %>% dplyr::summarise_all(dplyr::funs(sum)) %>% dplyr::ungroup() %>% as.data.frame() - + e_meta <- data.frame(Reaction=e_data$Reaction, stringsAsFactors = FALSE) %>% dplyr::left_join(dplyr::select(reactions, REACTION, ENZYME), by=c('Reaction'='REACTION')) %>% dplyr::rename(EC_Number=ENZYME) %>% dplyr::left_join(observed_comp_per_rxn, by="Reaction") - + # get # observable compounds per reaction subject to mass filter applied to compoundObj obs_comp <- dplyr::inner_join(comp_rxn, compounds, by=c('Compound'='COMPOUND')) if (!is.null(attr(compoundObj, "filters")) && !is.null(attr(compoundObj, "filters")$massFilt)) { thresh.min <- min(attr(compoundObj, "filters")$massFilt$threshold) thresh.max <- max(attr(compoundObj, "filters")$massFilt$threshold) - + if (toupper(db) == "METACYC") { obs_comp <- ftmsRanalysis:::metacyc_mass_filter(obs_comp, thresh.min, thresh.max) } else { stop(paste("Unknown database:", db)) } } - + obs_comp <- dplyr::group_by(obs_comp, Reaction) %>% dplyr::summarise(`N_Observable_Compounds`=dplyr::n_distinct(Compound)) e_meta <- dplyr::left_join(e_meta, obs_comp, by="Reaction") - - result <- as.reactionData(e_data, compoundObj$f_data, e_meta, edata_cname = "Reaction", - fdata_cname=getFDataColName(compoundObj), reaction_cname="Reaction", + + result <- as.reactionData(e_data, compoundObj$f_data, e_meta, edata_cname = "Reaction", + fdata_cname=getFDataColName(compoundObj), reaction_cname="Reaction", instrument_type=getInstrumentType(compoundObj), db=getDatabase(compoundObj)) - + #attributes from compoundObj to carry forward: # result <- ftmsRanalysis:::setDatabase(result, db) result <- ftmsRanalysis:::setGroupDF(result, getGroupDF(compoundObj)) -# result <- ftmsRanalysis:::setInstrumentType(result, getInstrumentType(compoundObj)) +# result <- ftmsRanalysis:::setInstrumentType(result, getInstrumentType(compoundObj)) result <- ftmsRanalysis:::setDataScale(result, "count") attr(result, "filters") <- attr(compoundObj, "filters") - + ## TODO: are there any other cnames that need to be carried through?? if (!is.null(attr(compoundObj, "cnames")$extraction_cname)) { attr(result, "cnames")$extaction_cname <- attr(compoundObj, "cnames")$extraction_cname } - + return(result) } diff --git a/R/mapPeaksToCompounds.R b/R/mapPeaksToCompounds.R index 108e3c8..72fd1d7 100644 --- a/R/mapPeaksToCompounds.R +++ b/R/mapPeaksToCompounds.R @@ -1,14 +1,14 @@ -#' Map peak FT-MS data to compounds -#' -#' Map peak level FT-MS data to compounds from MetaCyc. +#' Map peak FT-MS data to compounds +#' +#' Map peak level FT-MS data to compounds from MetaCyc. #' #' @param peakObj object of type peakData #' @param db database to map to, currently 'MetaCyc' (case insensitive) is the only valid option. This requires #' the MetaCycData package. #' @return compoundData object -#' +#' #' @author Amanda White -#' +#' #' @export mapPeaksToCompounds <- function(peakObj, db="MetaCyc") { if (!inherits(peakObj, "peakData")) { @@ -24,35 +24,35 @@ mapPeaksToCompounds <- function(peakObj, db="MetaCyc") { compounds <- mc_compounds %>% dplyr::rename(FORMULA=MF) # rm(mc_compounds) - + data("mc_compounds_per_formula") ## TODO make this in MetaCycData package compounds_per_formula <- mc_compounds_per_formula colnames(compounds_per_formula) <- c(getMFColName(peakObj), "Num_Compounds_Per_Formula") # rm(mc_compounds_per_formula) - + db_name <- "MetaCyc" - + # reassign molecular formulas using metacyc format suppressMessages(peakObj <- ftmsRanalysis:::assign_mf(peakObj, metacyc=TRUE)) } - + # get only peaks that have mass formulas e_meta <- peakObj$e_meta %>% - dplyr::filter_(lazyeval::interp(~!is.na(var), var = as.name(getMFColName(peakObj)))) %>% - dplyr::mutate_(tmp19302859032 = as.character(getMFColName(peakObj))) %>% + dplyr::filter(!is.na(.data[[getMFColName(peakObj)]])) %>% + dplyr::mutate(tmp19302859032 = as.character(getMFColName(peakObj))) %>% dplyr::filter(tmp19302859032 != "") %>% dplyr::select(-tmp19302859032) cmp.col <- dplyr::select(compounds, FORMULA, COMPOUND) - colnames(cmp.col) <- c(getMFColName(peakObj), "Compound") - + colnames(cmp.col) <- c(getMFColName(peakObj), "Compound") + # keep only rows that have a mapping in the compound database e_meta <- dplyr::inner_join(e_meta, cmp.col, by=getMFColName(peakObj)) # filter e_data to match e_meta peaks.to.keep <- unique(dplyr::select(e_meta, !!getEDataColName(peakObj), !!getMFColName(peakObj))) - + new_edata_colname <- getMFColName(peakObj) - + # identify if any compounds map to multiple masses. if so, an arbitrary unique ID column needs to be formed for e_data. if (anyDuplicated(peaks.to.keep[, getMFColName(peakObj)]) > 0) { warning("Multiple masses map to the same molecular formula/compound. Constructing a unique ID for e_data.") @@ -61,15 +61,15 @@ mapPeaksToCompounds <- function(peakObj, db="MetaCyc") { e_meta <- dplyr::left_join(peaks.to.keep[, c("ID", getMFColName(peakObj))], e_meta, by=getMFColName(peakObj)) peaks.to.keep <- dplyr::select(peaks.to.keep, -dplyr::matches(getMFColName(peakObj))) } - + e_data <- dplyr::left_join(peaks.to.keep, peakObj$e_data, by=getEDataColName(peakObj)) %>% dplyr::select(-dplyr::matches(getEDataColName(peakObj))) - + # construct resulting compoundData object - res <- as.compoundData(e_data, peakObj$f_data, e_meta, edata_cname=new_edata_colname, fdata_cname=getFDataColName(peakObj), + res <- as.compoundData(e_data, peakObj$f_data, e_meta, edata_cname=new_edata_colname, fdata_cname=getFDataColName(peakObj), mass_cname=getMassColName(peakObj), mf_cname=getMFColName(peakObj), compound_cname="Compound", - data_scale=getDataScale(peakObj), instrument_type=getInstrumentType(peakObj)) - + data_scale=getDataScale(peakObj), instrument_type=getInstrumentType(peakObj)) + # make a copy of column names attributes cnames.new <- attr(res, "cnames") cnames.old <- attr(peakObj, "cnames") @@ -85,6 +85,6 @@ mapPeaksToCompounds <- function(peakObj, db="MetaCyc") { # attr(res, "instrument_type") <- attr(peakObj, "instrument_type") # attr(res, "data_info") <- attr(peakObj, "data_info") res <- ftmsRanalysis:::setDatabase(res, db) - + return(res) -} \ No newline at end of file +} diff --git a/R/uniqueness_functions.R b/R/uniqueness_functions.R index 749330e..6249510 100644 --- a/R/uniqueness_functions.R +++ b/R/uniqueness_functions.R @@ -1,236 +1,236 @@ #' Determine Unique and Common Masses/Peaks for Two Groups -#' +#' #' Use number of samples for which a mass/peak is present to compare two groups and determine which peaks are uniquely expressed in each group -#' +#' #' @param edata_df data.frame giving samples expression profiles for samples belonging to one of two groups #' @param group_df data.frame giving sample names and column indicating group membership. Column indicating group membership should be named 'Group' and have exactly two unique values #' @param data_scale character string giving scale the data is on. Current acceptable values are: "log", "log2", "log10", "abundance", "pres" #' @param pres_thresh integer value indicating the minimum number of samples per group that are required for a peak to be considered present/observed in a group. #' @param absn_thresh integer value indicating the maximum number of samples per group that can be observed for a peak to be considered absent in a group. -#' +#' #' @name uniqueness_nsamps #' @author Lisa Bramer -#' +#' uniqueness_nsamps <- function(edata_df, group_df, data_scale, pres_thresh, absn_thresh){ - + # check that edata_df is data.frame # if(!inherits(edata_df, "data.frame")) stop("edata_df must be of class 'data.frame'") - + # check that group_df is data.frame # if(!inherits(group_df, "data.frame")) stop("group_df must be of class 'data.frame'") - + # check that group_df has two columns and one is title 'Group' # if(ncol(group_df) != 2) stop("group_df should be a data.frame with two columns") if(!("Group" %in% names(group_df))) stop("group_df must have one column named 'Group' giving sample group membership") - + # check that there are exactly two group levels # if(length(unique(group_df$Group)) != 2) stop("Group column in group_df must contain exactly two group levels") # check that data_scale is valid # # if(class(data_scale) != "character") stop("data_scale must be of class 'character'") # if(!(data_scale %in% c("log", "log2", "log10", "abundance", "pres"))) stop("data_scale value is not an invalid option.") - + # determine which column gives the samples in group_df # samp_colname = names(group_df)[which(names(group_df) != "Group")] - + # get unique group levels # grps = as.character(unique(group_df$Group)) - + # get sample names which belong to each group level # grp1_samps = group_df[which(group_df$Group == grps[1]), samp_colname] grp2_samps = group_df[which(group_df$Group == grps[2]), samp_colname] - + max_n_samps = max(c(length(grp1_samps), length(grp2_samps))) min_n_samps = min(c(length(grp1_samps), length(grp2_samps))) - + # ensure that pres_thresh and absn_thresh are integers # pres_thresh = as.integer(pres_thresh) absn_thresh = as.integer(absn_thresh) - + # check that pres_thresh is greater than 0 and less than min number of samples in groups # if(!(pres_thresh > 0 & pres_thresh <= min_n_samps)) stop("pres_thresh must be an integer greater than 0 and less than the minimum number of samples in a group") - + # check that absn_thresh is greater than or equal to 0 and less than the min number of samples in groups # if(!(absn_thresh >= 0 & absn_thresh <= min_n_samps)) stop("absn_thresh must be an integer greater than or equal to 0 and less than the minimum number of samples in a group") - + # check that absn_thresh is less than pres_thresh # if(!(absn_thresh < pres_thresh)) stop("absn_thresh must be less than pres_thresh") # if data is not in presence/absence form, convert to pres/abs (number or NA) # - + for(i in 1:ncol(edata_df)){ edata_df[which(edata_df[,i] == 0), i] = NA } - - + + # pull group membership column and ensure that order matches edata_df column order # ord_groupdf = group_df[match(names(edata_df), group_df[,samp_colname]),] - - + + # calculate the maximum (over the two groups) number of samples observed per group # numpres = data.frame(N_grp1 = apply(!is.na(edata_df[which(names(edata_df) %in% grp1_samps)]), 1, sum), N_grp2 = apply(!is.na(edata_df[which(names(edata_df) %in% grp2_samps)]), 1, sum) ) - - + + # construct results vector # res_vec = rep(NA, nrow(edata_df)) res_vec[which(apply(numpres, 1, min) >= pres_thresh)] = "Observed in Both" res_vec[which(numpres$N_grp1 >= pres_thresh & numpres$N_grp2 <= absn_thresh)] = paste("Unique to", grps[1], sep = " ") res_vec[which(numpres$N_grp1 <= absn_thresh & numpres$N_grp2 >= pres_thresh)] = paste("Unique to", grps[2], sep = " ") - + lvls <- c(paste("Unique to", grps), "Observed in Both") data.frame(uniqueness_nsamps = factor(res_vec, levels = lvls)) } #' Determine Unique and Common Masses/Peaks for Two Groups -#' +#' #' Use proportion of samples for which a mass/peak is present to compare two groups and determine which peaks are uniquely expressed in each group -#' +#' #' @param edata_df data.frame giving samples expression profiles for samples belonging to one of two groups #' @param group_df data.frame giving sample names and column indicating group membership. Column indicating group membership should be named 'Group' and have exactly two unique values #' @param data_scale character string giving scale the data is on. Current acceptable values are: "log", "log2", "log10", "abundance", "pres" #' @param pres_thresh numeric value between 0 and 1, inclusive, indicating the minimum proportion of samples per group that are required for a peak to be considered present/observed in a group. #' @param absn_thresh numeric value between 0 and 1, inclusive, indicating the maximum proportion of samples per group that can be observed for a peak to be considered absent in a group. -#' +#' #' @name uniqueness_prop #' @author Lisa Bramer -#' +#' uniqueness_prop <- function(edata_df, group_df, data_scale, pres_thresh, absn_thresh){ - + # check that edata_df is data.frame # if(!inherits(edata_df, "data.frame")) stop("edata_df must be of class 'data.frame'") - + # check that group_df is data.frame # if(!inherits(group_df, "data.frame")) stop("group_df must be of class 'data.frame'") - + # check that group_df has two columns and one is title 'Group' # if(ncol(group_df) != 2) stop("group_df should be a data.frame with two columns") if(!("Group" %in% names(group_df))) stop("group_df must have one column named 'Group' giving sample group membership") - + # check that there are exactly two group levels # if(length(unique(group_df$Group)) != 2) stop("Group column in group_df must contain exactly two group levels") - + # check that data_scale is valid # # if(class(data_scale) != "character") stop("data_scale must be of class 'character'") # if(!(data_scale %in% c("log", "log2", "log10", "abundance", "pres"))) stop("data_scale value is not an invalid option.") - + # determine which column gives the samples in group_df # samp_colname = names(group_df)[which(names(group_df) != "Group")] - + # get unique group levels # grps = as.character(unique(group_df$Group)) - + # get sample names which belong to each group level # grp1_samps = group_df[which(group_df$Group == grps[1]), samp_colname] grp2_samps = group_df[which(group_df$Group == grps[2]), samp_colname] - - + + # ensure that pres_thresh and absn_thresh are between 0 and 1 # - if(!(pres_thresh >= 0 & pres_thresh <= 1)) stop("pres_thresh must be a numeric value between 0 and 1 inclusive") - if(!(absn_thresh >= 0 & absn_thresh <= 1)) stop("absn_thresh must be a numeric value between 0 and 1 inclusive") - + if(!(pres_thresh >= 0 & pres_thresh <= 1)) stop("pres_thresh must be a numeric value between 0 and 1 inclusive") + if(!(absn_thresh >= 0 & absn_thresh <= 1)) stop("absn_thresh must be a numeric value between 0 and 1 inclusive") + # check that absn_thresh is less than pres_thresh # if(!(absn_thresh < pres_thresh)) stop("absn_thresh must be less than pres_thresh") # if data is not in presence/absence form, convert to pres/abs (number or NA) # - + for(i in 1:ncol(edata_df)){ edata_df[which(edata_df[,i] == 0), i] = NA } - - + + # pull group membership column and ensure that order matches edata_df column order # ord_groupdf = group_df[match(names(edata_df), group_df[,samp_colname]),] - - - + + + # calculate the maximum (over the two groups) number of samples observed per group # prop_pres = data.frame(prop_grp1 = apply(!is.na(edata_df[which(names(edata_df) %in% grp1_samps)]), 1, sum)/length(grp1_samps), prop_grp2 = apply(!is.na(edata_df[which(names(edata_df) %in% grp2_samps)]), 1, sum)/length(grp2_samps) ) - - + + # construct results vector # res_vec = rep(NA, nrow(edata_df)) res_vec[which(apply(prop_pres, 1, min) >= pres_thresh)] = "Observed in Both" res_vec[which(prop_pres$prop_grp1 >= pres_thresh & prop_pres$prop_grp2 <= absn_thresh)] = paste("Unique to", grps[1], sep = " ") res_vec[which(prop_pres$prop_grp1 <= absn_thresh & prop_pres$prop_grp2 >= pres_thresh)] = paste("Unique to", grps[2], sep = " ") - + lvls <- c(paste("Unique to", grps), "Observed in Both") data.frame(uniqueness_prop = factor(res_vec, levels=lvls)) } #' Determine Unique and Common Masses Between Two Groups -#' +#' #' Use a g-test to compare two groups and determine which peaks are uniquely expressed in each group based on a p-value threshold -#' +#' #' @param edata_df data.frame giving samples expression profiles for samples belonging to one of two groups #' @param group_df data.frame giving sample names and column indicating group membership. Column indicating group membership should be named 'Group' and have exactly two unique values #' @param data_scale character string giving scale the data is on. Current acceptable values are: "log", "log2", "log10", "abundance", "pres" #' @param pres_fn character string indicating the function to use when determining if a peak/compound is present for a group. Current options include "nsamps" and "prop". #' @param pres_thresh numeric value indicating the threshold (e.g. number of samples, proportion of samples, etc.), inclusive, that are required for a peak to be considered present/observed in a group. -#' @param pvalue_thresh p-value threshold at which masses with a g-test p-value less than or equal to \code{pval_threshold} are considered to be unique to the group with more observed proportion/number of samples, which also exceeds \code{pres_thresh} -#' +#' @param pvalue_thresh p-value threshold at which masses with a g-test p-value less than or equal to \code{pval_threshold} are considered to be unique to the group with more observed proportion/number of samples, which also exceeds \code{pres_thresh} +#' #' @name uniqueness_gtest #' @author Lisa Bramer -#' +#' uniqueness_gtest <- function(edata_df, group_df, data_scale, pres_fn, pres_thresh, pvalue_thresh = 0.05){ # check that edata_df is data.frame # if(!inherits(edata_df, "data.frame")) stop("edata_df must be of class 'data.frame'") - + # check that group_df is data.frame # if(!inherits(group_df, "data.frame")) stop("group_df must be of class 'data.frame'") - + # check that group_df has two columns and one is title 'Group' # if(ncol(group_df) != 2) stop("group_df should be a data.frame with two columns") if(!("Group" %in% names(group_df))) stop("group_df must have one column named 'Group' giving sample group membership") - + # check that data_scale is valid # # if(class(data_scale) != "character") stop("data_scale must be of class 'character'") # if(!(data_scale %in% c("log", "log2", "log10", "abundance", "pres"))) stop("data_scale value is not an invalid option.") - + # check that pres_fn is valid # if(!(pres_fn %in% c("nsamps", "prop"))) stop("Specified 'pres_fn' is not a valid option.") - + # determine which column gives the samples in group_df # samp_colname = names(group_df)[which(names(group_df) != "Group")] - + # get unique group levels # grps = as.character(unique(group_df$Group)) - + # get sample names which belong to each group level # grp1_samps = group_df[which(group_df$Group == grps[1]), samp_colname] grp2_samps = group_df[which(group_df$Group == grps[2]), samp_colname] - + min_n_samps = min(c(length(grp1_samps), length(grp2_samps))) - + # ensure that pres_thresh is valid # if(pres_fn == "nsamps"){ pres_thresh = as.integer(pres_thresh) if(!(pres_thresh >= 0 & pres_thresh <= min_n_samps)) stop("pres_thresh must be an integer between 1 and the minimum number of samples in a group") } if(pres_fn == "prop"){ - if(!(pres_thresh >= 0 & pres_thresh <= 1)) stop("pres_thresh must be a numeric value between 0 and 1 inclusive") + if(!(pres_thresh >= 0 & pres_thresh <= 1)) stop("pres_thresh must be a numeric value between 0 and 1 inclusive") } - + # change 0's to NA's for the g-test # for(i in 1:ncol(edata_df)){ edata_df[which(edata_df[,i] == 0), i] = NA } - + # pull group membership column and ensure that order matches edata_df column order # ord_groupdf = group_df[match(names(edata_df), group_df[,samp_colname]),] - + # run g-test on data # gtest_res = gtest.standard(data = as.matrix(edata_df), group = ord_groupdf$Group) - + # summarize presence by group # if(pres_fn == "nsamps"){ numpres = data.frame(N_grp1 = apply(!is.na(edata_df[which(names(edata_df) %in% grp1_samps)]), 1, sum), @@ -242,17 +242,17 @@ uniqueness_gtest <- function(edata_df, group_df, data_scale, pres_fn, pres_thres numpres = data.frame(N_grp1 = apply(!is.na(edata_df[which(names(edata_df) %in% grp1_samps)]), 1, sum)/length(grp1_samps), N_grp2 = apply(!is.na(edata_df[which(names(edata_df) %in% grp2_samps)]), 1, sum)/length(grp2_samps) ) - + } - + max_val_grp = apply(numpres, 1, max) min_val_grp = apply(numpres, 1, min) - + # construct results vector # res_vec = rep(NA, nrow(edata_df)) res_vec[which(min_val_grp >= pres_thresh)] = "Observed in Both" res_vec[which(gtest_res$pvals <= pvalue_thresh & max_val_grp >= pres_thresh)] = paste("Unique to", gtest_res$major.group[which(gtest_res$pvals <= pvalue_thresh & max_val_grp >= pres_thresh)], sep = " ") - + lvls <- c(paste("Unique to", grps), "Observed in Both") out_df = data.frame( uniqueness_gtest = factor(res_vec, levels = lvls), @@ -261,37 +261,37 @@ uniqueness_gtest <- function(edata_df, group_df, data_scale, pres_fn, pres_thres dplyr::bind_cols( numpres ) - + return(out_df) } #' G-test function -#' +#' #' G-test function -#' +#' #' @param data p x n matrix, where n = # of observations and p = # of variables to be tested #' @param group an n x 1 vector specifying group membership -- group names can be of type numeric or character -#' +#' #' @name gtest.standard #' @author Lisa Bramer -#' +#' gtest.standard = function(data, group){ - + ## store some basic summary statistics ## p = nrow(data) n = ncol(data) - grps = as.factor(group) + grps = as.factor(droplevels(group)) num.grps = length(levels(grps)) - + ## basic tests before proceeding ## if(length(group)!=n)stop("Group vector length does not match number of rows in the data provided") if(num.grps < 2)stop("Must have at least two groups to conduct test") - + ## store the group names ## grp.names = levels(grps) - + grp.ns = NULL ## calculate group sample sizes ## for(i in 1:num.grps){ @@ -299,21 +299,21 @@ gtest.standard = function(data, group){ curdat = grps[grps==curgrp] grp.ns[i] = length(curdat) } - - + + ## results placeholders ## Gstat = NULL pvalue = NULL major.group = NULL - + ## run the Gtest on each variable ## for(j in 1:p){ - + ## pull data for current variable ## test.data = unlist(data[j,]) obs.miss = matrix(0, nrow = 2, ncol = num.grps) - - ## calculate observed number of missing/non-missing data values per group ## + + ## calculate observed number of missing/non-missing data values per group ## ## first row is the number of missing values, second row is the number of nonmissing values ## ## each column corresponds to a group ## for(i in 1:num.grps){ @@ -321,10 +321,10 @@ gtest.standard = function(data, group){ cur.dat = test.data[grps==cur.grp] obs.miss[,i] = c(sum(is.na(cur.dat)),sum(!is.na(cur.dat))) } - + ## summarize the total number of missing and non-missing values over all groups ## tot.miss = apply(obs.miss,1,sum) - + ## If all data is missing or all data is present, standard calculation will fail. ## ## In these cases, there is no evidence of a signficant difference, so we set the p-value to 1 ## if(min(tot.miss) > 0){ @@ -333,13 +333,13 @@ gtest.standard = function(data, group){ ## expected value is the overall proportion of missing/non-missing times number of samples in the group ## for(i in 1:num.grps){ exp.miss[,i] = (tot.miss/n)*grp.ns[i] - } + } } - + if(min(tot.miss) > 0){ ## calculate preliminary value for each cell ## prelim.g = obs.miss*log(obs.miss/exp.miss) - + ## G-statistic sums over non-empty observed cells and then multiplies by 2 ## Gstat[j] = 2*sum(prelim.g[!is.na(prelim.g)]) df = num.grps - 1 @@ -350,9 +350,9 @@ gtest.standard = function(data, group){ pvalue[j] = 1 major.group[j] = "Common to Both" } - + } - + return(list(pvals = pvalue, major.group = major.group)) } diff --git a/tests/testthat/test_comparisonMatrix.R b/tests/testthat/test_comparisonMatrix.R index bba79d0..333a0ef 100644 --- a/tests/testthat/test_comparisonMatrix.R +++ b/tests/testthat/test_comparisonMatrix.R @@ -6,32 +6,32 @@ context("comparisonMatrix function") test_that("creating comparison matrix works correctly, when group_DF is absent", { data("examplePeakData") - + ngroups <- length(unique(examplePeakData$f_data$SampleID)) max.pairs <- choose(ngroups, 2) - + # all comparisons - all <- comparisonMatrix(ftmsObj = examplePeakData, comparisons = "all", control = NULL) + all <- ftmsRanalysis:::comparisonMatrix(ftmsObj = examplePeakData, comparisons = "all", control = NULL) expect_true(nrow(all) == 2) expect_true(ncol(all) == max.pairs) - + # one-factor changing comparisons - expect_error(one <- comparisonMatrix(ftmsObj = examplePeakData, comparisons = "one-factor", control = NULL), + expect_error(one <- comparisonMatrix(ftmsObj = examplePeakData, comparisons = "one-factor", control = NULL), regexp="The 'one-factor' specification cannot be used without a group data frame") # specific comparisons spec <- comparisonMatrix(ftmsObj = examplePeakData, comparisons = list(c("EM0011_sample","EM0061_sample"),c("EW0113_sample","EW0163_sample")), control = NULL) expect_true(nrow(spec) == 2) expect_true(ncol(spec) == 2) - + # compare against control contr <- comparisonMatrix(ftmsObj = examplePeakData, comparisons = "control", control = "EM0011_sample") expect_true(nrow(contr) == 2) expect_true(ncol(contr) == ngroups - 1) - + # Trying to compare groups not found in dataset expect_error(comparisonMatrix(ftmsObj = examplePeakData, comparisons = list(c("EM0011sample","EM0061_sample"),c("EW0113_sample","EW0163_sample")), control = NULL), regexp = "not all groups specified in pairs parameter were found in the data") - + #invalid data_scale value: should throw an error expect_error(comparisonMatrix(ftmsObj = examplePeakData, comparisons = "mymethod", control = NULL), regexp = "check that comparisons argument is") }) @@ -39,7 +39,7 @@ test_that("creating comparison matrix works correctly, when group_DF is absent", test_that("creating comparison matrix works correctly, when group_DF is present", { data("exampleProcessedPeakData") - + ngroups <- length(unique(attr(exampleProcessedPeakData, "group_DF")$Group)) max.pairs <- choose(ngroups, 2) @@ -47,17 +47,17 @@ test_that("creating comparison matrix works correctly, when group_DF is present" all <- comparisonMatrix(ftmsObj = exampleProcessedPeakData, comparisons = "all", control = NULL) expect_true(nrow(all) == 2) expect_true(ncol(all) == max.pairs) - + # one-factor changing comparisons one <- comparisonMatrix(ftmsObj = exampleProcessedPeakData, comparisons = "one-factor", control = NULL) expect_true(nrow(one) == 2) expect_true(ncol(one) == 4) - + # specific comparisons spec <- comparisonMatrix(ftmsObj = exampleProcessedPeakData, comparisons = list(c("M_S","W_S"),c("M_C","W_C")), control = NULL) expect_true(nrow(spec) == 2) expect_true(ncol(spec) == 2) - + # compare against control contr <- comparisonMatrix(ftmsObj = exampleProcessedPeakData, comparisons = "control", control = "M_C") expect_true(nrow(contr) == 2) @@ -65,7 +65,7 @@ test_that("creating comparison matrix works correctly, when group_DF is present" # Trying to compare groups not found in dataset expect_error(comparisonMatrix(ftmsObj = exampleProcessedPeakData, comparisons = list(c("M_S","W_S"),c("M_C","WC")), control = NULL), regexp = "not all groups specified in pairs parameter were found in the data") - + #invalid data_scale value: should throw an error expect_error(comparisonMatrix(ftmsObj = exampleProcessedPeakData, comparisons = "mymethod", control = NULL), regexp = "check that comparisons argument is") }) diff --git a/tests/testthat/test_divideByGroupComparisons.R b/tests/testthat/test_divideByGroupComparisons.R index ef060f1..269b9d8 100644 --- a/tests/testthat/test_divideByGroupComparisons.R +++ b/tests/testthat/test_divideByGroupComparisons.R @@ -5,79 +5,79 @@ context("divideByGroupComparisons function") test_that("basic tests on divideByGroupComparisons with all comparisons", { data("exampleProcessedPeakData") - + comparisons <- ftmsRanalysis:::comparisonMatrix(exampleProcessedPeakData, "all") - - grpComp <- divideByGroupComparisons(exampleProcessedPeakData, comparisons="all") - + + grpComp <- divideByGroupComparisons(exampleProcessedPeakData, comparisons="all") + expect_true(inherits(grpComp, "list")) expect_true(length(grpComp) == ncol(comparisons)) - + i <- 3 testSubset <- grpComp[[i]] expect_true(inherits(testSubset, "groupComparison")) - + grps <- comparisons[,i] samples <- as.character(dplyr::filter(getGroupDF(exampleProcessedPeakData), Group %in% grps)$SampleID) expect_true(all(samples %in% colnames(testSubset$e_data))) - + expect_true(all(samples %in% getGroupDF(testSubset)$SampleID)) expect_true(all(getGroupDF(testSubset)$SampleID %in% samples)) expect_true(all(grps %in% getGroupDF(testSubset)$Group)) expect_true(all(getGroupDF(testSubset)$Group %in% grps)) - + }) test_that("divideByGroupComparisons works without a groupDF", { data("examplePeakData") - + comparisons <- ftmsRanalysis:::comparisonMatrix(examplePeakData, comparisons="control", control="EM0061_sample") - - grpComp <- divideByGroupComparisons(examplePeakData, comparisons="control", control="EM0061_sample") - + + grpComp <- divideByGroupComparisons(examplePeakData, comparisons="control", control="EM0061_sample") + expect_true(inherits(grpComp, "list")) expect_true(length(grpComp) == ncol(comparisons)) - + n_samples <- length(unique(examplePeakData$f_data[, getFDataColName(examplePeakData)])) expect_true(length(grpComp) == n_samples-1) - + i <- 5 testSubset <- grpComp[[i]] expect_true(inherits(testSubset, "groupComparison")) - + grps <- comparisons[,i] samples <- grps expect_true(all(samples %in% colnames(testSubset$e_data))) - + expect_true(all(samples %in% getGroupDF(testSubset)$SampleID)) expect_true(all(getGroupDF(testSubset)$SampleID %in% samples)) expect_true(all(grps %in% getGroupDF(testSubset)$Group)) expect_true(all(getGroupDF(testSubset)$Group %in% grps)) - + }) test_that("divideByGroupComparisons with one-factor comparisons", { data("exampleProcessedPeakData") - + comparisons <- ftmsRanalysis:::comparisonMatrix(exampleProcessedPeakData, "one-factor") - - grpComp <- divideByGroupComparisons(exampleProcessedPeakData, comparisons="one-factor") - + + grpComp <- divideByGroupComparisons(exampleProcessedPeakData, comparisons="one-factor") + expect_true(inherits(grpComp, "list")) expect_true(length(grpComp) == ncol(comparisons)) - + i <- 3 testSubset <- grpComp[[i]] expect_true(inherits(testSubset, "groupComparison")) - + grps <- comparisons[,i] samples <- as.character(dplyr::filter(getGroupDF(exampleProcessedPeakData), Group %in% grps)$SampleID) expect_true(all(samples %in% colnames(testSubset$e_data))) - + expect_true(all(samples %in% getGroupDF(testSubset)$SampleID)) expect_true(all(getGroupDF(testSubset)$SampleID %in% samples)) expect_true(all(grps %in% getGroupDF(testSubset)$Group)) expect_true(all(getGroupDF(testSubset)$Group %in% grps)) - + })