Safer purrr::map2 for lists with names out of order

We can do

library(tidyverse)
map2(evens, odds[names(evens)], str_c, sep=' ')
#$a
#[1] "2 11"

#$b
#[1] "4 5"

#$c
#[1] "6 7"

#$d
#[1] "8 9"

If both the list names are unordered, loop through the sorted names of one of the list, extract both the elements and concatenate

map(sort(names(evens)), ~ str_c(evens[[.x]], odds[[.x]], sep= ' '))

Or create an identifier for the order, then order the list elements in both the list and concatenate with map2

i1 <- order(names(evens)) # not sure if this should be avoided
map2(evens[i1], odds[i1], str_c, sep=" ")

bind_rows matches the names, so you could bind_rows and then map (although this imposes additional constraints on what's in the lists)

library(tidyverse)

bind_rows(evens, odds) %>% 
  map(paste, collapse = ' ')

# $`a`
# [1] "2 11"
# 
# $b
# [1] "4 5"
# 
# $c
# [1] "6 7"
# 
# $d
# [1] "8 9"

Just write a helper function to clean it up

namemap <- function(.x, .y, .f, ...) {
  n <- order(unique(names(.x), names(.y)))
  map2(.x[n], .y[n], .f, ...)
}
namemap(odds, evens, paste)

Basically there's no primitive in purrr that will do this automatically for you. And when it's this easy to do, there doesn't seem to be much point.

Tags:

R

Purrr