mardi 21 septembre 2021

Can someone help me writing a nested for loop in Rstudio? research example provided

I am a graduate student and I have a background in Chemistry, not computer science or coding. Most things I've been able to learn via the internet and tutorials, but today I'm writing you all because I have been trying to write a nested for loop for a few weeks and I feel very stuck. Any help is appreciated.

The data:

  • I have two data sets (Table 1 and Table 2) that are list of compounds detected by mass spectrometry.
  • Each list of compounds contains three very basic terms - the index (i or j), retention time (RT min), and mass-to-charge ion ratio (m/z). The fourth term is the numerical ID assigned for each compound by each lab (ID_T1 or ID_T2).
  • Table 1 was collected and analyzed by Lab 1. Table 1 is indexed by i.
  • Table 2 was collected by Lab 1 but analyzed by Lab 2. Table 2 is indexed by j.

The comparison: Two questions that I am to answer using this code are

  1. "Does the m/z from Table 1[i] match the m/z from Table 2[j]?"
  2. "Does the RT(min) from Table 1[i] match the RT(min) from Table 2[j]?”

The criteria: In order to answer question 1 – MZ Matching – I would use the following criteria:

|(Table_1[i,1] – Table_2[j,1])/ Table_1[i,1])*106| < 3 ppm

In order to answer question 2 – RT Matching – I would use the following criteria:

|Table_1[i,2] – Table_2[j,2]| < 0.9

The output: I would like each positive match (i.e. matching RT and MZ) from the for loop to be written into a new table. I don’t know if it is possible to write the match result (TRUE/FALSE) into the existing tables. I would like to be able to preserve some data from the newly combined rows (Lab ID’s from Lab 1 and Lab 2)

The progress:

for (i in 1:length(Table_1$RT)) 
  for (j in 1:length(Table_2$RT))
    {if abs(Table_1$RT[i]- Table_2$RT[j])<0.9 ==TRUE)
  {Table_3$RTResult<-(abs(Table_1$RT[i]- Table_2$RT[j])<0.9)
 Table_3$ID_T1 <- i
 Table_3$ID_T2 <- j}
}
  else
  {print(i)
      print(j)}}

Currently most of my error messages are Error: unexpected symbol or Error: unexpected '}' so I don't know what I'm doing wrong or if I'm even on the right track! Help!!

I have attached pictures so as to visualize the problem.enter image description here Thanks in Advance for any solutions you may have! If you have a similarenter image description here example of this I would LOVE to see it bsaleeby <3

Data table examples and Result examples on the left - "For" loop plan on the right

Aucun commentaire:

Enregistrer un commentaire