cbind named vectors in R by name
Asked Answered
G

1

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.

Gender answered 12/8, 2017 at 11:24 Comment(0)
D
15

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
Darciedarcy answered 12/8, 2017 at 11:26 Comment(1)
I was sure it was super obvious! Thanks a lotGender

© 2022 - 2024 — McMap. All rights reserved.