9

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.

Dave2e
  • 22,192
  • 18
  • 42
  • 50
ltr
  • 332
  • 2
  • 9

1 Answers1

14

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
akrun
  • 874,273
  • 37
  • 540
  • 662