Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we iterate over two lists with purrr (not simultaneously)?

Tags:

r

purrr

Consider that I have a function f(x,y) that takes two argument and two lists

  • x_var = list('x','y','z')
  • and 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!

like image 825
ℕʘʘḆḽḘ Avatar asked Sep 01 '17 15:09

ℕʘʘḆḽḘ


People also ask

Is purrr faster than for loops?

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.

Is Lapply faster than map?

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).

What does pmap do in r?

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.

What does map_ df() do in r?

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.


1 Answers

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"
like image 123
Richard Telford Avatar answered Nov 08 '22 17:11

Richard Telford