seq_along of two lists, make a dataframe and keep the name of the lists

63 Views Asked by At

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?

2

There are 2 best solutions below

0
jpsmith On

You can use expand.grid to get the combinations from the two lists, then apply to paste the values together:

apply(expand.grid(unlist(mylist_1), unlist(mylist_2)), 1,
      paste, collapse = "_")

Output:

# [1] "a1_b1" "a2_b1" "a3_b1" "a4_b1" "a5_b1" "a6_b1" "a1_b2" "a2_b2" "a3_b2" "a4_b2" "a5_b2" "a6_b2" "a1_b3" "a2_b3"
# [15] "a3_b3" "a4_b3" "a5_b3" "a6_b3" "a1_b4" "a2_b4" "a3_b4" "a4_b4" "a5_b4" "a6_b4" "a1_b5" "a2_b5" "a3_b5" "a4_b5"
# [29] "a5_b5" "a6_b5" "a1_b6" "a2_b6" "a3_b6" "a4_b6" "a5_b6" "a6_b6" "a1_b7" "a2_b7" "a3_b7" "a4_b7" "a5_b7" "a6_b7"
# [43] "a1_b8" "a2_b8" "a3_b8" "a4_b8" "a5_b8" "a6_b8" "a1_b9" "a2_b9" "a3_b9" "a4_b9" "a5_b9" "a6_b9"
10
r2evans On

An alternative is outer:

c(outer(mylist_1[[1]], mylist_2[[1]], function(a, b) paste(a, b, sep = "_")))
#  [1] "a1_b1" "a2_b1" "a3_b1" "a4_b1" "a5_b1" "a6_b1" "a1_b2" "a2_b2" "a3_b2" "a4_b2" "a5_b2" "a6_b2" "a1_b3" "a2_b3" "a3_b3" "a4_b3" "a5_b3" "a6_b3" "a1_b4"
# [20] "a2_b4" "a3_b4" "a4_b4" "a5_b4" "a6_b4" "a1_b5" "a2_b5" "a3_b5" "a4_b5" "a5_b5" "a6_b5" "a1_b6" "a2_b6" "a3_b6" "a4_b6" "a5_b6" "a6_b6" "a1_b7" "a2_b7"
# [39] "a3_b7" "a4_b7" "a5_b7" "a6_b7" "a1_b8" "a2_b8" "a3_b8" "a4_b8" "a5_b8" "a6_b8" "a1_b9" "a2_b9" "a3_b9" "a4_b9" "a5_b9" "a6_b9"