R/translate_taxa.R

#' Translate to target taxonomy.
#'
#' @description Using a translation table as generated by \code{generate_table} and modified by the user,
#' translate the target composition data to the new taxonomic groupings.
#'
#' @param input_table The composition data table, consisting of \code{id_var} columns, indicating spatial and compositional data, with one taxon in each column.
#' @param translation The translation table, generated by \code{generate_table}.
#' @param id_cols The location columns, for example \code{c('x', 'y')}, representing the spatial coordinates for the data.
#'
#' @return A \code{data.frame} with indicator columns as identified in \code{id_cols} and once column for each of the unique taxa.
#'
#' @importFrom stats formula
#' @importFrom reshape2 melt dcast
#' @export
#'
#' @examples {
#'   \dontrun{
#'     calib_trans <- translate_taxa(calib_dialect,
#'                                   pol_table,
#'                                   id_cols = colnames(calib_dialect)[1:10])
#'   }
#' }

translate_taxa <- function(input_table, translation, id_cols) {

  agg_fun <- paste0(paste0(id_cols, collapse = ' + '), '~ match')

  long <- input_table %>%
    reshape2::melt(variable.name = 'target',
                   value.name = 'values',
                   id.vars = id_cols) %>%
    inner_join(translation %>% filter(!is.na(match)),
               by = 'target') %>%
    select(one_of(id_cols), 'match', 'values') %>%
    filter(!'values' == 0) %>%
    reshape2::dcast(stats::formula(agg_fun),
                    fun.aggregate = sum,
                    value.var = 'values',
                    drop = TRUE)

    return(long)

}
PalEON-Project/stepps-cal documentation built on May 14, 2019, 8:20 a.m.