Reputation: 7
I have two data frames, A and B.
First I want to match two columns from B(id and type) to A.
If they have the same elements then I want to call all the other information in A to new dataframe C.
For example
A
id type info1 info2 info3 info4
a t1 * ~ ~ ~
b t5 * ~ ~ ~
c t3 * ~ ~ ~
a t2 * ~ ~ ~
b t3 * ~ ~ ~
B
id % type
a .2 t1
b .15 t2
c .1 t3
a and c have both same types in A and B
So I want to create a new data frame C with all the other columns which a and c have in A,
id type info1 info2 info3 info4
A t1 * ~ ~ ~
C t3 * ~ ~ ~
I tried
C = merge(A, C, by = c("type", "id"))
but I think it shows all the type and id which are both in A and B.
Upvotes: 0
Views: 63
Reputation: 59425
Looks like you want to extract from A only those rows where id and type match in B. You can use merge for this:
C <- merge(A,B[,c("id","type")])
C
# id type info1 info2 info3 info4
# 1 a t1 * ~ ~ ~
# 2 c t3 * ~ ~ ~
You don't need by=...
in this because the only columns in the second argument are id
and type
, and merge works on all common columns by default.
Upvotes: 1