Skip to content

Instantly share code, notes, and snippets.

@multimeric
Created March 25, 2021 04:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save multimeric/f905601c75a132b98563920f3c0a9b22 to your computer and use it in GitHub Desktop.
Save multimeric/f905601c75a132b98563920f3c0a9b22 to your computer and use it in GitHub Desktop.
require(purrr)
require(dplyr)
require(stringr)
#' Maps over the keys and values of a vector, but expects the function to return
#' a named vector with "key" and "value" entries. These will become the names
#' and values of the final vector. Think of this as like a Python dictionary
#' comprehension: it takes an iterable and produces a dictionary.
#'
#' @param l a vector to map over
#' @param func the function to apply over that vector, which must return a `list(key=?, value=?)`
#' @param map_keys logical. If TRUE, then use `imap` which provides the keys as the second element to the function
#'
#' @examples
#' c(1,2,3) %>% kv_map(~list(key=letters[[.]], value=.))
#' c(1,2,3) %>% kv_map(function(x){ list(key=letters[[x]], value=x) })
#' c(a=1,b=2,c=3) %>% kv_map(~list(key=str_c(.y, '²'), value=.x), map_keys=T)
kv_map = function(l, func, map_keys=F){
mapper = ifelse(map_keys, purrr::imap, purrr::map)
mapper(l, func) %>%
bind_rows() %>%
pull(var='value', name='key')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment