This is conceptually similar to zip() in Python, or R functions purrr::transpose() and data.table::transpose() (albeit, accepting elements in ... instead of a single list), with one crucial difference: if the provided objects are named, then matching is done by names, not positions.

zip_lists(...)

Arguments

...

R lists or atomic vectors, optionally named.

Value

A inverted list

Details

All arguments supplied must be of the same length. If positional matching is required, then all arguments provided must be unnamed. If matching by names, then all arguments must have the same set of names, but they can be in different orders.

Examples

gradients <- list("grad_for_wt_1", "grad_for_wt_2", "grad_for_wt_3")
weights <- list("weight_1", "weight_2", "weight_3")
str(zip_lists(gradients, weights))
#> List of 3
#>  $ :List of 2
#>   ..$ : chr "grad_for_wt_1"
#>   ..$ : chr "weight_1"
#>  $ :List of 2
#>   ..$ : chr "grad_for_wt_2"
#>   ..$ : chr "weight_2"
#>  $ :List of 2
#>   ..$ : chr "grad_for_wt_3"
#>   ..$ : chr "weight_3"
str(zip_lists(gradient = gradients, weight = weights))
#> List of 3
#>  $ :List of 2
#>   ..$ gradient: chr "grad_for_wt_1"
#>   ..$ weight  : chr "weight_1"
#>  $ :List of 2
#>   ..$ gradient: chr "grad_for_wt_2"
#>   ..$ weight  : chr "weight_2"
#>  $ :List of 2
#>   ..$ gradient: chr "grad_for_wt_3"
#>   ..$ weight  : chr "weight_3"

names(gradients) <- names(weights) <- paste0("layer_", 1:3)
str(zip_lists(gradients, weights[c(3, 1, 2)]))
#> List of 3
#>  $ layer_1:List of 2
#>   ..$ : chr "grad_for_wt_1"
#>   ..$ : chr "weight_1"
#>  $ layer_2:List of 2
#>   ..$ : chr "grad_for_wt_2"
#>   ..$ : chr "weight_2"
#>  $ layer_3:List of 2
#>   ..$ : chr "grad_for_wt_3"
#>   ..$ : chr "weight_3"

names(gradients) <- paste0("gradient_", 1:3)
try(zip_lists(gradients, weights)) # error, names don't match
#> Error in zip_lists(gradients, weights) : 
#>   All names of arguments provided to `zip_lists()` must match. Call `unname()` on each argument if you want positional matching
# call unname directly for positional matching
zip_lists(unname(gradients), unname(weights))
#> [[1]]
#> [[1]][[1]]
#> [1] "grad_for_wt_1"
#> 
#> [[1]][[2]]
#> [1] "weight_1"
#> 
#> 
#> [[2]]
#> [[2]][[1]]
#> [1] "grad_for_wt_2"
#> 
#> [[2]][[2]]
#> [1] "weight_2"
#> 
#> 
#> [[3]]
#> [[3]][[1]]
#> [1] "grad_for_wt_3"
#> 
#> [[3]][[2]]
#> [1] "weight_3"
#> 
#>