Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rbind 2 vectors of different lengths by their names

Tags:

r

I have 2 vectors of different lengths:

vec1 <- rnorm(18, mean = 0.0018, sd = 0.0001)
names(vec1) <- c("CSF", "D10", "D13", "D16", "D18", "D1", "D21", "D22", "D3", "D5", "D7", "D8", "FGA", "PD", "PE", "TH", "TP", "vWA")

vec2 <- rnorm(20, mean = 0.0022, sd = 0.0002)
names(vec2) <-  c("CSF", "D10", "D12", "D13", "D16", "D18", "D19", "D1", "D21", "D22", "D2", "D2S", "D3", "D5", "D7", "D8", "FGA", "TH", "TP", "vWA") 

I need to rbind these vectors by their names. When a name in one vector does not exist in the other, that should produce an NA.

Is there a simple way to do that?

like image 756
vitor Avatar asked Nov 30 '25 08:11

vitor


2 Answers

I find it easier to deal with data.frames rather than vectors. I'd do something like this:

merge(stack(vec1), stack(vec2), by="ind", all=TRUE)

#    ind    values.x    values.y
# 1  CSF 0.001904712 0.001969627
# 2   D1 0.001794500 0.002450328
# 3  D10 0.001761172 0.002144368
# 4  D13 0.001792968 0.002037505
# 5  D16 0.001715555 0.002240566
# 6  D18 0.001770989 0.002459609
# 7  D21 0.001697098 0.002292614
# 8  D22 0.001673249 0.002057277
# 9   D3 0.001824599 0.002025163
# 10  D5 0.001762133 0.002066801
# 11  D7 0.001938889 0.002218919
# 12  D8 0.001804742 0.001930666
# 13 FGA 0.001723325 0.002153777
# 14  PD 0.001864792          NA
# 15  PE 0.001581331          NA
# 16  TH 0.001803464 0.002136557
# 17  TP 0.001737948 0.002294142
# 18 vWA 0.001681773 0.002168390
# 19 D12          NA 0.001907538
# 20 D19          NA 0.002243354
# 21  D2          NA 0.002040115
# 22 D2S          NA 0.002230522
like image 154
Arun Avatar answered Dec 02 '25 23:12

Arun


Try this, better to use data.frame

df1 = data.frame(v=vec1,n=names(vec1))
df2 = data.frame(v=vec2,n=names(vec2))
df = merge(df1,df2,by="n",all=TRUE)
> head(df)
    n         v.x         v.y
1 CSF 0.001772553 0.001985266
2  D1 0.001818434 0.001974980
3 D10 0.001658625 0.002339643
4 D13 0.001877724 0.002099361
5 D16 0.001738895 0.002249619
6 D18 0.001691192 0.002274924
like image 44
statquant Avatar answered Dec 02 '25 21:12

statquant