I have a tricky problem to access the string values of a list as argument to purr functions.
My goal is to concatenate all permutations of the string elements of two vectors (to use in an output filename) which I put into one input list:
target.labels <- c("Prefix_A", "Prefix_B")
features.sets <- c("Suffix_X", "Suffix_Y")
input.list <- expand.grid(x=target.labels, y=features.sets)
The expected result should look like:
"Prefix_A-Suffix_X" "Prefix_B-Suffix_X" "Prefix_A-Suffix_Y" "Prefix_B-Suffix_Y"
Here's what I tried:
library(dplyr)
library(purrr)
fun1 <- function(x,y) { paste0(c(x, y), collapse = "-") }
fun2 <- function(x,y) { paste(x, y, sep = "-") }
fun3 <- function(x,y) { glue::glue("x = {x}, y = {y}") }
input.list %>% pmap_chr(fun1)
## [1] "1-1" "2-1" "1-2" "2-2"
input.list %>% pmap_chr(fun2)
## [1] "1-1" "2-1" "1-2" "2-2
input.list %>% pmap_chr(fun3)
## [1] "x = 1, y = 1" "x = 2, y = 1" "x = 1, y = 2" "x = 2, y = 2"
input.list %>% pmap_chr(~paste(.x, .y, sep = "-"))
## [1] "1-1" "2-1" "1-2" "2-2"
As you can see, the purr::pmap functions only retrieve the elements' index values instead of the string values. On the other side, it may not be specific to purr as the apply functions show the same problem:
mapply(fun1, input.list$x, input.list$y)
## [1] "1-1" "2-1" "1-2" "2-2"
One hunch is that somehow, the hidden c() function in paste0() or paste() prevents the access of the string values - but only in combination with purr:pmap, not with purr:map2!
So this works:
map2_chr(.x = input.list$x, .y = input.list$y, ~paste(.x, .y, sep = "-"))
## [1] "Prefix_A-Suffix_X" "Prefix_B-Suffix_X" "Prefix_A-Suffix_Y"
## [4] "Prefix_B-Suffix_Y"
My hunch is that this issue may have something to do with NSE (non-standard evaluation) but I just can't figure it out because the purr:map2 works as expected.
I would be grateful for a good explanation why this happens - and how to make it work with purr:pmap.