# ----------------------------------------------------------------------------------
# METHOD: invert( hash )
# produces a hash with the values as keys and the keys as values
# ----------------------------------------------------------------------------------
#' Create/invert a hash.
#'
#' THIS IS AN EXPERIMENTAL FUNCTION. THE IMPLEMENTATION OR INTERFACE MAY CHANGE
#' IN THE FUTURE.
#'
#' `invert` exchanges the keys and values of a hash.
#'
#' `inverted.hash` is a constructor method that directly makes an inverted
#' hash.
#'
#' @param x A [hash()] object
#' @param ... Arguments passed to the [hash()] function.
#'
#' @details
#' Each element of the `values(x)` becomes a key in a new hash; the
#' associatedis coerced to a key value is the
#' The value becomes the associated key.
#'
#' For `inverted.hash`, a hash is created thnn inverted. It is defined
#' as:
#'
#' ` function(...) invert(hash(...)) `
#'
#'
#' @return A hash object with: keys as the unique elements of `values(x)`
#' and values as the associated \code{keys{x}}
#'
#' @author Christopher Brown
#'
#' @seealso See also \code{link{hash}} and [make_keys()]
#'
#' @examples
#'
#' h <- hash( a=1, b=1:2, c=1:3 )
#' invert(h)
#'
#' inverted.hash( a=1, b=1:2, c=1:3 )
#'
#' @rdname invert
#' @docType methods
#' @export
setGeneric( "invert", function(x) standardGeneric( "invert" ) )
#' @rdname invert
setMethod( 'invert', 'hash',
function(x) {
h <- hash()
for( k in keys(x) ) {
for( v in make_keys(x[[k]]) ) {
if ( ! has_key(h,v) ) h[[v]] <- k
else h[[v]] <- append( h[[v]], k )
}
}
h
}
)
#' @rdname invert
#' @export
inverted.hash <- function(...) invert( hash(...) )
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.