0

I was wondering if there is an efficient way to convert each element (each with different length) in my List to a column in a data frame to achieve my Desired_output?

I tried the following without success:

dplyr::bind_cols(List) 

Note: This data is toy, a functional answer is appreciated.

List <- list(`1000`=letters[1:2], `2000`=letters[1:3], `3000`=letters[1:4])

Desired_output <-
data.frame(`1000`= c(letters[1:2],"",""),
           `2000`= c(letters[1:3],""), 
           `3000`= letters[1:4])

Simon Harmel
  • 927
  • 2
  • 9

1 Answers1

1

You could try this.

library(purrr)

l <- list(`1000`=letters[1:2], `2000`=letters[1:3], `3000`=letters[1:4])

# get max lengths across all list items
max_len = max(lengths(l))

# using purrr::modify add as many empty characters needed until each
# item has the same number of rows as the item with the most

l = modify(l, function(f) {
  f = c(f, rep("", max_len-length(f)))
})
as.data.frame(l)

  X1000 X2000 X3000
1     a     a     a
2     b     b     b
3           c     c
4                 d
Jamie
  • 1,793
  • 6
  • 16