Can we iterate over two lists with purrr (not at the same time)?

Note that I have a function f(x,y)that takes two arguments and two lists

  • x_var = list('x','y','z')
  • and y_var = list('a','b')

Is there a function purrrthat allows me to iterate over each combination of one element in x_varand one element in y_var? Ie f(x,a), f(x,b), f(y,a), f(y,b)etc.

The usual solution would be to write a loop, but I'm wondering if there is a shorter one here (perhaps p purrr.

Thank!

+4
source share
4 answers

You can use one of the functions cross*along with map:

map(cross2(x_var, y_var), unlist)
+9
source

The basic function R works here expand.grid.

expand.grid(x=x_var, y=y_var) %>% {paste(.$x, .$y)}
+4

You can attach your challenges 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"
+3
source

If x_varand y_varare atomic vectors or arrays, and the function returns an atomic vector of known length, you can use the basic function R outer:

outer(x_var, y_var, FUN = f)

This will return an array with dimensions c(dim(x_var), dim(y_var)). Dimension names are similarly combined. For instance:

x_var <- setNames(1:3, c("a", "b", "c"))
y_var <- setNames(4:5, c("d", "e"))
outer(x_var, y_var, '+')
#   d e
# a 5 6
# b 6 7
# c 7 8
+3
source

Source: https://habr.com/ru/post/1684907/


All Articles