Problem: I have a list of named vectors. The names are not always the same but I'd like to correctly stack them into a matrix which has a row for each vector and a column for each name.
Note - the input vectors may vary in length and may have differing names. It can be any number of vectors but my example shows 2.
This is not homework. I'm working on fixing a bug in a R package that uses sapply to create the vectors and then make the matrix but that ignores the names and then causes issues. Instead, I thought about using lapply to create the vectors but then still stuck on how to combine them. The package has no dependency on dplyr so I can't use bind_rows.
v1 <- c(5,6)
v2 <- c(7,8)
names(v1) <- c("x1", "x2")
names(v2) <- c("x1", "x3")
results <- list(v1, v2)
# desired output
(deisred <- structure(c(5, 7, 6, NA, NA, 8), .Dim = 2:3, .Dimnames = list(
NULL, c("x1", "x2", "x3"))))
#> x1 x2 x3
#> [1,] 5 6 NA
#> [2,] 7 NA 8
# I can do this with dplyr but want to remove dependency on dplyr
as.matrix(dplyr::bind_rows(results))
#> x1 x2 x3
#> [1,] 5 6 NA
#> [2,] 7 NA 8
# problem - disregards the name mismatch
do.call(rbind, results)
#> x1 x2
#> [1,] 5 6
#> [2,] 7 8
Created on 2022-03-30 by the reprex package (v2.0.1)