Steve Reno
Steve Reno

Reputation: 1384

pmap over lists of differing length

I am trying to determine how I might use the dplyr pmap function applied to lists of differing length.

A very simple example of what I would like to do would be the following

list_1 <- list(1, 2, 3)

list_2 <- list(1, 2)

list_3 <- list(1, 2, 3, 4, 5)


pmap(list(list_1, list_2, list_3), ~ ..1 + ..2 + ..3)

Where the result above would be a list of length length(list_1) * length(list_2) * length(list_3) containing the sum of all combinations of the 3 lists

My actual application is a bit more complicated in that I am trying to fit glm models where list_1 is the response list_2 and list_3 being other glm function inputs.

Upvotes: 2

Views: 488

Answers (1)

IceCreamToucan
IceCreamToucan

Reputation: 28695

pmap doesn't generate all combinations, it just applies a function to the first element of each list element, then the second, etc. You need expand.grid (or similar)

l.combs <- expand.grid(list_1, list_2, list_3)
l.combs[] <- lapply(l.combs, unlist)
rowSums(l.combs)

Or with pmap

library(tidyverse)
l.combs <- expand.grid(list_1, list_2, list_3)
pmap(l.combs, ~ ..1 + ..2 + ..3)

Edit: Here's an example with glm that "works" but is obviously nonsense statistically

list_1 <- replicate(3, runif(10), simplify = F)

list_2 <- replicate(2, runif(10), simplify = F)

list_3 <- replicate(5, runif(10), simplify = F)

l.combs <- expand.grid(list_1, list_2, list_3)
pmap(l.combs, ~ glm(..1 ~ ..2 + ..3))

Upvotes: 6

Related Questions