dan
dan

Reputation: 6314

Convert a list of vectors of different lengths to a data frame

Couldn't find any solution to this question online, but apologies if I missed it.

I have a list of several vectors (all character in this example), of different lengths:

ll <- list(f1 = c("a","b","c"),f2 = c("d","e"),f3 = "f")

I want to convert it into a data.frame that will cover all combinations of the lists elements. So the resulting data.frame will be:

data.frame(f1 = rep(f1,2), f2 = rep(f2,3), f3 = rep(f3,6))

Is there any function that achieves that?

Upvotes: 1

Views: 90

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389235

expand.grid should work in this case -

expand.grid(ll)

#  f1 f2 f3
#1  a  d  f
#2  b  d  f
#3  c  d  f
#4  a  e  f
#5  b  e  f
#6  c  e  f

Another similar alternative would be purrr::cross_df.

purrr::cross_df(ll)

Upvotes: 1

Related Questions