I am probably missing something very obvious, but I can’t seem to find a way to do this. I would like to will merge multiple vectors (or dataframes?) of different lengths into a dataframe by matching values of vector elements with each other and putting them into same row positions, filling rows left empty with NAs. I have tried the solution from qpcR (cbind.na) but it doesn’t produce expected outcome.
reproducible example:
x<-c("1","2","a","b")
y<-c("1","2","3","4","5","6","b")
z<-c("3","4","5","6","a")
expected output:
x y z
[1,] 1 1 NA
[2,] 2 2 NA
[3,] NA 3 3
[4,] NA 4 4
[5,] NA 5 5
[6,] NA 6 6
[7,] a NA a
[8,] b b NA
>Solution :
You could try this. It is similar to the answer by Paul Stafford Allen in that it starts with the unique values. I’ve put them in a list to allow for easy iteration, so it will be straightforward to extend to more columns.
l <- list(x = x, y = y, z = z)
dat <- data.frame(
unique_vals = sort(unique(unlist(l)))
)
dat[names(l)] <- lapply(l, \(x) {
x[match(dat$unique_vals, x)]
})
# unique_vals x y z
# 1 1 1 1 <NA>
# 2 2 2 2 <NA>
# 3 3 <NA> 3 3
# 4 4 <NA> 4 4
# 5 5 <NA> 5 5
# 6 6 <NA> 6 6
# 7 a a <NA> a
# 8 b b b <NA>
I kept the unique_vals column so it’s clear what’s going on but you may want to remove it.