Sub-setting data in R using 2 data tables

I'm trying to, ultimately, find max / min values in "DS" for multiple values of "P" in Perf for different properties "API". The "DS" set is 882 x 8 while Perf is 81 x 6. I have the problematic code below I've run that uses a "for" loop. Note that when API <- 1, the code does not stop at i <= imax, but only at imax. When API is anything but 1, the code pulls the wrong property and does not identify the correct values from DS. In no situation have I been able to pull more than the data at imax. I have tried "apply" and numerous other alternatives. I am a rank beginner with R so I'd appreciate some help. I have linked the data below as well. Thanks in advance, David C



Survey <- loadWorkbook("Rtestdatawellsurveys2.xlsx")
PerfInfo <- loadWorkbook("Rtestdataperfs.xlsx")

#Simplify names
DS <- readWorksheet(Survey, sheet = 1, startRow = 0, startCol = 0,
endRow = 882, endCol = 8)
Perf <- readWorksheet(PerfInfo, sheet = 1, startRow = 0, startCol = 0,
endRow = 81, endCol = 6)

#Select Property and Subset Data

API <- 2
Survey <- DS$API == API
Perfs <- Perf$API == API
S <- DS[Survey,"MD", ]
P <- Perf[Perfs,"Depths", ]

z<- 0

for(i in P) {

z <- z + 1

#Property that SHOULD be found by code,
#Note when API > 1, the code returns the incorrect property name

WellName <- Perf$Well[Perf$API == API]

#find depths greater and less than "i"
#Note this returns the CORRECT subset of data

MDL <- which(DS$MD[DS$API == API] <= i)
MDH <- which(DS$MD[DS$API == API] >= i)

#find max and mins of variables listed
#Note this returns the INCORRECT values when API >1

MDU <- max(DS[MDL,"MD", ])
MDO <- min(DS[MDH,"MD", ])

#at this point, when API <- 1, the output is correct, but the loop
#only returns values at imax (last value of "P"), so majority of solutions
#are missing.

#when API is greater than 1, the output is INCORRECT for property name,
#MDU, MDO and any other "max/min" related properties, but MDL and MDH
#are correct. Again, the loop only returns values at imax.