Merge vectors of different lengths to dynamic matrix

Viewed 36

How can I merge 5 vectors together into one dynamic/flexible matrix?

  V1 <- c(13, 31, 54)
  name1 <- c("a", "b2", "c")

  V2 <- c(17, 27, 34, 52)
  name2 <- c("a", "b1", "b2", "c")

  V3  <- c(19, 25, 33, 47, 58, 44)
  name3 <- c("a", "b1", "b2", "b3", "c", "d")

  V4  <- c(13, 29, 35, 56)
  name4 <- c("a", "b1", "b2", "c")

  V5<-c(21, 35, 67, 82, 96)
  name5<-c("d", "c", "b3", "b1", "b2")

And create a matrix like this:

enter image description here

1 Answers

We can load the objects into the global environment with mget based on the pattern of object names i.e. those object names that starts with (^) 'V' followed by one or more digits (\\d+) at the end ($) of the string. Then, append NA at the end of each of the list element based on the max lengths of the list

lst1 <- mget(ls(pattern = '^V\\d+$'))
t(sapply(lst1, `length<-`, max(lengths(lst1))))

If we need the names as well

lst2 <- mget(ls(pattern = '^name\\d+$'))
out <- xtabs(unlist(lst1) ~ rep(seq_along(lst1), lengths(lst1)) + 
         unlist(lst2))
names(dimnames(out)) <- NULL

Or another option is map2 from purrr

library(purrr)    
map2_dfr(lst1, lst2, setNames)

-output

# A tibble: 5 x 6
#     a    b2     c    b1    b3     d
#  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1    13    31    54    NA    NA    NA
#2    17    34    52    27    NA    NA
#3    19    33    58    25    47    44
#4    13    35    56    29    NA    NA
#5    NA    96    35    82    67    21
Related