Search code examples
rvectorcbind

How to cbind vectors of different length in R?


I need to combine some named numeric vectors in R into a data frame. I tried cbind.na as suggestet in another question, but it would not take names into account. Example:

v1 <- c(1,5,6,7)
names(v1) <- c("milk", "flour", "eggs", "sugar")
v2 <- c(2,3)
names(v2) <- c("fish", "chips")
v3 <- c(5,7,4)
names(v3) <- c("chips", "milk", "sugar")

The data frame should look like this

       v1    v2     v3
milk   1     NA     7
flour  5     NA     NA
eggs   6     NA     NA
sugar  7     NA     4
fish   NA    2      NA
chips  NA    3      5

I can't figure out how to solve this in R.


Solution

  • This is a join, best done with data.table or other add-ins, but (especially for smallish arrays) can readily be performed in base R by creating an array of all the names and using it to index into the input arrays:

    s <- unique(names(c(v1,v2,v3)))
    x <- cbind(v1=v1[s], v2=v2[s], v3=v3[s])
    rownames(x) <- s
    print(x)
    
          v1 v2 v3
    milk   1 NA  7
    flour  5 NA NA
    eggs   6 NA NA
    sugar  7 NA  4
    fish  NA  2 NA
    chips NA  3  5