Reputation: 61
I was hoping to get some help over this problem. I have a vector X
with 2,000 elements such that:
X<- c("A12","B5","B8","B19","A32","A25","B11","A2","A41","B51"......)
I extracted the IDs from the vector(A
IDs and B
IDs) separately. Now I have two vectors, A
and B
. This step is necessary because the process of obtaining A_values
and B_values
is different, so I needed to separate the two IDs into two vectors:
A<-c("A12","A32","A25","A2","A41".....)
B<-c("B5","B8","B19","B11","B51"....)
After this I obtained the values corresponding to their ids:
A_values <- c(15,21,22,6,2....)
B_values <-c(3,14,16,25,13....)
Now my problem is to merge the A_values
and B_values
vectors according to the original indices of Ids as they were in the original vector X
. The new X_values
vector should be:
X_values<-c(15,3,14,16,21,22,25,6,2,25,13.....)
Any help would be truly appreciated.
Upvotes: 1
Views: 227
Reputation: 886948
We can use the match
ing index concatenated for 'A', 'B'
c(A_values, B_values)[match(X, c(A, B))]
#[1] 15 3 14 16 21 22 25 6 2 13
X<- c("A12","B5","B8","B19","A32","A25","B11","A2","A41","B51")
A<-c("A12","A32","A25","A2","A41")
B<-c("B5","B8","B19","B11","B51")
A_values <- c(15,21,22,6,2)
B_values <- c(3,14,16,25,13)
Upvotes: 0
Reputation: 388817
You can create a named vector and then subset them using X
:
c(setNames(A_values, A), setNames(B_values, B))[X]
#A12 B5 B8 B19 A32 A25 B11 A2 A41 B51
# 15 3 14 16 21 22 25 6 2 13
Use unname
or as.numeric
/as.integer
to remove the names if not needed.
Upvotes: 1