Home > Software design >  Creating data.table from a list of unequal vector lengths
Creating data.table from a list of unequal vector lengths

Time:10-16

I am looking to create a data.table from a list of unequal vectors, but instead of repeating the values for the "shorter" vector, I want it to be filled with NAs. I have one possible solution, but it repeats values and does not retain the NA as needed.

Example:

library(data.table)
my_list <- list(A = 1:4, B = letters[1:5])  
as.data.table(do.call(cbind, my_list))

as.data.table(do.call(cbind, my_list))
   A B
1: 1 a
2: 2 b
3: 3 c
4: 4 d
5: 1 e

But I want it to look like:

as.data.table(do.call(cbind, my_list))
   A B
1: 1 a
2: 2 b
3: 3 c
4: 4 d
5: NA e

Thank you!

CodePudding user response:

We need to make the lengths same by appending NA at the end of the list elements having lesser length than the max length

mx <- max(lengths(my_list))
as.data.table(do.call(cbind, lapply(my_list, `length<-`, mx)))

-output

      A B
1:    1 a
2:    2 b
3:    3 c
4:    4 d
5: <NA> e

Instead of cbind/as.data.table, setDT is more compact

setDT(lapply(my_list, `length<-`, mx))[]
    A B
1:  1 a
2:  2 b
3:  3 c
4:  4 d
5: NA e

CodePudding user response:

You may use stringi::stri_list2matrix to make all the list length equal.

my_list |>
  stringi::stri_list2matrix() |>
  data.table::as.data.table() |>
  type.convert(as.is = TRUE) |>
  setNames(names(my_list))

#    A B
#1:  1 a
#2:  2 b
#3:  3 c
#4:  4 d
#5: NA e
  • Related