This is a small section of my actual data set.
1 2 3 4 5
57.033 57.0332 57.0333 57.0339 57.03332
57.033 57.033 57.0335 59.0490 59.04901
59.0489 59.048 59.0490589 60.0806 60.08
60.0805 60 60.08 60 60.08059
60.08053 60.080 60.08 61.0366 61.03947
A second matrix of same structure.
mz2
1 2 3 4 5
17.26 16.95225 17 17.84 17.79
14 141 143 632 629
630 63 631.337 241.5272 239
539 41 413 412 412
41 240 241 640 56
I need to compare the first value in col 1 with all values in all columns and if they match my criteria I should add the value in the first row of that particular column. This will happen in iteration. I then check for the second row in col 1 and match against all values in all columns and if they match the criteria, then add them at row 2 of the particular column.
I tried using for loops but it is quite confusing.
This is my attempt:
x.mz1<-matrix(0,5,5)
b1.mz=mz[,1] ##mz is my sample data above
b2.mz=mz2[,1]
for (i in length(b1.mz))
{
one.mz=b1.mz[i]
one.2=b2.mz[i]
for (j in 2:ncol(mz))
{
two.1=mz[,j]
two=mz2[,j]
for (k in 1:length(two.1))
{
sec.mz=two.1[k]
sec=two[k]
cond1[k]<-one.mz-two.1<0.000005
cond2[k]<-one.2-two<10
cond.check<-cbind(cond1[k],cond2[k])
cond.chc<-rbind(cond.check)
browser()
}
cond.chk.sum<-apply(cond.chc,1,sum)
sum.check<-sum(cond.chk.sum==2,na.rm=T)
if (sum.check==1)
{
x.mz1[i,j]=sec.mz
}
What I tried in my code: I tried to generate a logical matrix from all the iterations and after all rows in col 2 are checked for the criteria, there will be a logical matrix and when the matrix is generated it will be of size 5x2 for both conditions. Then when both conditions are TRUE, I add the col 2 value to row 1 if I am comparing first value in col 1.
I hope it is clear as I am quite confused after trying out all the looping structures back and forth. Is there an easier way to do this without using so many loops? using lappy or some other function.
output: not exact values but to give an idea of what I expect as output.
1 2 3 4 5
57.03326875 57.03329 0 57.033 57
57.03329688 0 0 0 59.049
59.04894556 60.0805 59.049 60 0
60.0805355 0 0 60.080 60.080
60.08053673 61.039281 0 60.09 61.0839
the first col is my col 1 in the main matrix and to this all other columns are calculated. if I find the one value from all the rows that match then i add it to the row and corresponding column from where the value belongs. 0's mean no no value matched for this value in col 1 from all the rows in that column.