I have two lists and I want all the elements of the one list to be combined with all the elements of the second list. I want to create a dataframe with column names of those combinations. I am not able to keep the names of the lists while indexing by using the seq_along function.
My two lists
mylist_2 <-list(c("b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9"))
mylist_1 <-list(c("a1", "a2", "a3", "a4", "a5", "a6"))
#making a vector with the length of multuplying the two:
mylist_f <- vector("list", length = length(mylist_1)*length(mylist_2))
I want to have a dataframe and the column names will be their combination
datafr <- expand.grid(i = seq_along(mylist_2), j = seq_along(mylist_1))[2:1]
## an under score will connect the indexing
data_fr <- apply(data_fr, 1, paste, collapse = "_")
names(mylist_f) <- datafr
What I get is:
>[1] "1_1" "1_2" "1_3" "1_4" "1_5" "1_6" "1_7" "1_8" "1_9" "2_1" "2_2" "2_3" "2_4" "2_5" "2_6"
[16] "2_7" "2_8" "2_9" "3_1" "3_2" "3_3" "3_4" "3_5" "3_6" "3_7" "3_8" "3_9" "4_1" "4_2" "4_3"
[31] "4_4" "4_5" "4_6" "4_7" "4_8" "4_9" "5_1" "5_2" "5_3" "5_4" "5_5" "5_6" "5_7" "5_8" "5_9"
[46] "6_1" "6_2" "6_3" "6_4" "6_5" "6_6" "6_7" "6_8" "6_9"
I am getting the indexing of the two lists but I would like to keep the name of the lists,I would like to get:
"a1_b1", "a1_b2", "a1_b3",......"a1_b9",
"a2_b1", "a2_b2",....."a2_b9", "a3_b1", "a3_b2", "a3_b3"....."a3_b9",.....
Any ideas how to keep the name of the lists on the columns of the dataframe?
You can use
expand.gridto get the combinations from the two lists, thenapplytopastethe values together:Output: