Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Is there any function that achieves that?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading