R/append_values.R

Defines functions append_values

Documented in append_values

#' Append Values
#'
#' Appends values to a value that has been previously encoded by
#' `encode_value()`, using a key generated by `make_encoding_key()`.
#'
#' @param encoded_value The old encoded value, as generated by `encode_value()`.
#' @param values_to_append A vector of values to add to the encoded value.
#' @param prime_key An encoding key, as generated by `make_encoding_key()`.
#'
#' @usage append_values(encoded_value, values_to_append, prime_key)
#'
#' @return A double containing an integer with the new encoded value.
#' @export
#' @seealso [primr::encode_value()]
#' @seealso [primr::make_encoding_key()]
#' @md
#'
#' @examples
#' # Add "Arthropod" to the previously encoded value.
#' new_encoded_value <- append_values(6, "Arthropod", c(Fish = 2, Mammal = 3, Bird = 5, Arthropod = 7))
append_values <- function(encoded_value, values_to_append, prime_key) {
  decoded_values <- primr::decode_value(encoded_value, prime_key)

  if(!sum(!values_to_append %in% names(prime_key)) == 0) {
    stop("Argument values_to_append contains values not present in argument prime_key. Generate a new key using function make_encoding_key or add the values to the exisiting key using function add_values_to_key.")
  }

  if (sum(!values_to_append %in% decoded_values) == 0) {
    warning("Argument encoded_value already contains argument values_to_append. No change made.")
    return(encoded_value)
  }

  unique_values_to_append <- values_to_append[!values_to_append %in% decoded_values]

  new_encoded_value <- prod(prime_key[names(prime_key) %in% unique_values_to_append]) * encoded_value

  return(new_encoded_value)
}
JonasEngstrom/primr documentation built on June 9, 2022, 9:43 p.m.