Reputation: 59
I have two lists of fits generated by lm and I would like to combine them element-wise.
Right now, I have something like: fits1 = list(fit1, fit2, fit3) (where fit1, fit2, and fit3 are models generated by lm) and fits2 = list(fit4, fit5, fit6).
What I would like to do is produce a list combined elementwise: list(list(fit1, fit4), list(fit2, fit5), list(fit3, fit6)).
I found some stuff about how to combine lists element-wise but all the solutions I've seen have required switching to a dataframe and you cannot include elements of class lm in a dataframe.
Thank you!
Upvotes: 1
Views: 197
Reputation: 35594
Another base
solution
asplit(rbind(list1, list2), MARGIN = 2)
It's equivalent to
asplit(cbind(list1, list2), MARGIN = 1)
Test
fits1 <- list("fit1", "fit2", "fit3")
fits2 <- list("fit4", "fit5", "fit6")
asplit(rbind(fits1, fits2), 2)
[[1]]
[[1]]$fits1
[1] "fit1"
[[1]]$fits2
[1] "fit4"
[[2]]
[[2]]$fits1
[1] "fit2"
[[2]]$fits2
[1] "fit5"
[[3]]
[[3]]$fits1
[1] "fit3"
[[3]]$fits2
[1] "fit6"
Upvotes: 2
Reputation:
I think Map
will give you what you are looking for.
fits1 <- list("fit1", "fit2", "fit3")
fits2 <- list("fit4", "fit5", "fit6")
Map(list, fits1, fits2)
Result:
[[1]]
[[1]][[1]]
[1] "fit1"
[[1]][[2]]
[1] "fit4"
[[2]]
[[2]][[1]]
[1] "fit2"
[[2]][[2]]
[1] "fit5"
[[3]]
[[3]][[1]]
[1] "fit3"
[[3]][[2]]
[1] "fit6"
In tidyverse
speak, that would use purrr
.
library(purrr)
map2(fits1, fits2, list)
Upvotes: 4