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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With