R: compare 1 columns from two matrices and get the output if they are the same
Hi guys,
assume I have two matrices, and I want to get the third, C. If value of the first column of A is the same to a value of the first column in B, when this condition is TRUE I want to add to a final C the third column of A
A = matrix( c(5, 0, 0,3, 1, 5, 7,3,4), nrow=3, ncol=3)
B = matrix( c(2, 0, 0,3, 1, 5, 7,3,4,0,2,1), nrow=4, ncol=2)
> A
[,1] [,2] [,3]
[1,] 5 3 7
[2,] 0 1 3
[3,] 0 5 4
> B
[,1] [,2]
[1,] 2 1
[2,] 0 5
[3,] 0 7
[4,] 3 3
output C:
0 5 3
0 7 4
I managed to extract those which are equal, but I don't know how to add the third column of A.
s=B[B[,1]%in%A[,1],]
s
[,1] [,2]
[1,] 0 5
[2,] 0 7
I tried apply(), my output is following. Not sure why I get 1 and 1?
> a=cbind(s, apply(s, 2, function(z) any(A[,1] %in% B[,1])))
> a
[,1] [,2] [,3]
[1,] 0 5 1
[2,] 0 7 1
thank you,
• 128 views
•
link
0 answers
No answers yet.
Log in to answer this question.
How do you get:
But not:
Condition "value of the first column of A is the same to a value of the first column in B" is still
TRUE. Probably you want to bind matrices side by side and then filter according matching columns, but your example number of rows differ.Where is your matrix C? You can simply make a key of common terms to look into both matrix and cbind.
How is that connected to bioinformatics?