user1378122
user1378122

Reputation: 105

simple vector manipulation

I'm pretty sure this will be trivial - but for life of me no elegant solution comes to mind....

I have two vectors of potentially differing lengths:

a <- c(1,2,3,4,5)
names(a)<-c("a","b","c","d","e")


b <- c(10,20,30)
names(b)<-c("a","b","d")

I would like to generate x such that:

x

 a  b  c  d  e 
10 20 NA 30 NA

For context - this is for a comparison plot where I am comparing different models some of which share some parameters - and I want to ensure that equivalent values are lined up.

Thinking about it more though in the scenario where:

a <- c(1,2,3,4,5)
names(a)<-c("a","b","c","d","e")


b <- c(10,20,30,1000)
names(b)<-c("a","b","d","x")

I would need to return 2 new vectors:

x1
 a  b  c  d  e  x
 1  2  3  4  5  NA

and

x2
  a   b   c   d   e     x
 10  20  NA  30  NA  1000

Thus giving me 2 series to plot in parallel - I hope at least some of that makes sense.

If anyone has any suggestions on how I might accomplish the above their assistance would be hugely appreciated.

Thanks for reading

D

Upvotes: 3

Views: 154

Answers (3)

plannapus
plannapus

Reputation: 18759

I would do:

a <- c(1,2,3,4,5)
names(a)<-c("a","b","c","d","e")
b <- c(10,20,30)
names(b)<-c("a","b","d")

unique(c(names(a),names(b))) -> d
x <- rep(NA,length(d))
names(x) <- d
x[d%in%names(b)] <- b   # for your first case
x
 a  b  c  d  e 
10 20 NA 30 NA 

And it also works for your second case:

a <- c(1,2,3,4,5)
names(a)<-c("a","b","c","d","e")
b <- c(10,20,30,1000)
names(b)<-c("a","b","d","x")

unique(c(names(a),names(b))) -> d
x1 <- x2 <- rep(NA,length(d))
names(x1) <- names(x2) <- d
x1[d%in%names(a)] <- a
x2[d%in%names(b)] <- b
x1
a  b  c  d  e  x 
1  2  3  4  5 NA 
x2
 a    b    c    d    e    x 
10   20   NA   30   NA 1000 

Upvotes: 1

JACKY88
JACKY88

Reputation: 3557

For x, try

> setNames(b[names(a)], names(a))
 a  b  c  d  e 
10 20 NA 30 NA 

For x1 and x2, try

> allnames <- union(names(a), names(b))
> setNames(a[allnames], allnames)
 a  b  c  d  e  x 
 1  2  3  4  5 NA 
> setNames(b[allnames], allnames)
  a    b    c    d    e    x 
 10   20   NA   30   NA 1000 

Upvotes: 2

Andrie
Andrie

Reputation: 179578

Add a dash of setNames to vector subsetting and shake well.

setNames(b[names(a)], names(a))
 a  b  c  d  e 
10 20 NA 30 NA 

This works on your example data, but you might have to experiment whether it is more generally applicable.

Upvotes: 1

Related Questions