Search code examples
rvectorcbind

cbind named vectors in R by name


I have two named vectors similar to these ones:

x <- c(1:5)
names(x) <- c("a","b","c","d","e")

t <- c(6:10)
names(t) <- c("e","d","c","b","a")

I would like to combine them so to get the following outcome:

  x  t
a 1 10
b 2  9
c 3  8
d 4  7
e 5  6

Unfortunately when I run cbind(x,t) the result just combines them in the order they are disregarding the names of t and only keeping those of x. Giving the following result:

  x  t
a 1  6
b 2  7
c 3  8
d 4  9
e 5 10

I'm pretty sure there must be an easy solution, but I cannot find it. As this passage is part of a long and tedious loop (and the vectors I'm working with are much longer), it is important to have the least convoluted and quicker to compute options.


Solution

  • We can use the names of 'x' to change the order the 't' elements and cbind with 'x'

    cbind(x, t = t[names(x)])
    #  x  t
    #a 1 10
    #b 2  9
    #c 3  8
    #d 4  7
    #e 5  6