Reputation: 1004
I have two character vectors of length 5:
x <- c("B","A","D","K","F")
y <- c("A","C","D","F","E")
The characteristics of these vectors are the following:
x
element "B"
is more important than "A"
)What I want is to "merge" these 2 vectors in order to obtain a new vector z
of length 5 which contains the most important non duplicate elements of vectors x
and y
, respectively, giving a priority to x
in case of ties.
To be clearer, the logic of my program should work as follows:
x
and y
: if they're different, put them inside z
x
and y
: if there's a value that is already inside z
, ignore it. Else, put it in.x
or y
, ignore it. Else, put it inside z
.x
and y
.length(z)==5
In my example it would work as follows:
B
and A
inside z
C
inside z
D
inside z
(which is now of length 4)K
and F
: if we put both, length(z)
will be 6, so take just K
as it's inside x
(priority)The resulting vector would be z = c("B","A","C","D","K")
.
I could transform the vectors in lists or whatever, but I would like to avoid using loops.
Upvotes: 0
Views: 78
Reputation: 1481
Here is a solution:
x <- c("B","A","D","K","F")
y <- c("A","C","D","F","E")
df=(t(data.frame(x,y)))
(result=unique(as.vector(df))[1:5])
[1] "B" "A" "C" "D" "K"
Thanks for nice detailed explanation.
Upvotes: 1