Home > database >  how to combine two lists and assign keys to them
how to combine two lists and assign keys to them

Time:12-26

I have 2 list:

comb_test <- list(c(7, 8))

col_type_list <- list(c("bin", "bin"))

I would like to get a new list that would look like this:

common.list <- list(list(id = 7, type = "bin"), list(id = 8, type = "bin")) 

CodePudding user response:

How about lapply through the length of one of your vectors...

lapply(1:length(comb_test[[1]]), function(x) list(id = comb_test[[1]][[x]], type = col_type_list[[1]][[x]]))

[[1]]
[[1]]$id
[1] 7

[[1]]$type
[1] "bin"


[[2]]
[[2]]$id
[1] 8

[[2]]$type
[1] "bin"

CodePudding user response:

You could use purrr::transpose(). If your data consists of vectors embedded in length-one lists, as in your example:

library(purrr)

comb_test <- list(c(7, 8))
col_type_list <- list(c("bin", "bin"))

transpose(list(id = comb_test[[1]], type = col_type_list[[1]]))

If you’re instead working with flattened lists, you can omit [[1]]:

comb_test <- list(7, 8)
col_type_list <- list("bin", "bin")

transpose(list(id = comb_test, type = col_type_list))

Result:

[[1]]
[[1]]$id
[1] 7

[[1]]$type
[1] "bin"


[[2]]
[[2]]$id
[1] 8

[[2]]$type
[1] "bin"
  • Related