Consider that I have a function f(x,y)
that takes two argument and two lists
x_var = list('x','y','z')
y_var = list('a','b')
Is there a purrr
function that allows me to iterate every combination of one element in x_var
and one element in y_var
? That is, doing f(x,a)
, f(x,b)
, f(y,a)
, f(y,b)
etc.
The usual solution would be to write a loop, but I wonder if there is more concise here (possibly with purrr
.
Thanks!
Among other applications, these other functions can make it so you don't need to use the unlist() function when working with the output. The purrr library is an incredible tool to help make your code faster and more efficient by eliminating for loops and taking advantage of R's functional abilities.
the output should be the same and the benchmarks I made seem to show that lapply is slightly faster (it should be as map needs to evaluate all the non-standard-evaluation input).
The pmap() functions work slightly differently than the map() and map2() functions. In map() and map2() functions, you specify the vector(s) to supply to the function. In pmap() functions, you specify a single list that contains all the vectors (or lists) that you want to supply to your function.
map() returns a list or a data frame; map_lgl() , map_int() , map_dbl() and map_chr() return vectors of the corresponding type (or die trying); map_df() returns a data frame by row-binding the individual elements.
You can nest your calls to map
library(purrr)
map(x_var, function(x) {
map(y_var, paste, x)
})
[[1]]
[[1]][[1]]
[1] "a x"
[[1]][[2]]
[1] "b x"
[[2]]
[[2]][[1]]
[1] "a y"
[[2]][[2]]
[1] "b y"
[[3]]
[[3]][[1]]
[1] "a z"
[[3]][[2]]
[1] "b z"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With