I am currently trying to read out data from multiple data frames (A1-A8), which all have the same structure, with a for loop. Within the for loop, I would like to extract data meeting a certain condition (in this case, a specific depth). I tried this with subset and if-else. The problem I am facing is, that in case this condition is not met, the for loop is interrupted and the following steps are not carried out. Here's the example:
Depth <- c(40,60,70,80,85,90)
D2H <- c(-60,-65,-63,-67,-58,-66)
A1 <- data.frame(Depth, D2H)
for (i in 1:8) {
Ax <- get((paste("A",i,sep="")))# reads in the dataframe
A_40[i] <- subset(Ax$D2H, Ax$Depth == 40) #writes the value of D2H at depth 40 into the new vector
A_60[i] <- subset(Ax$D2H, Ax$Depth == 60)
}
So if for example data frame A3 doesn't contain Depth = 40, the for loop is interrupted. How can I overcome this problem? Wrong approach?
I hope I described the problem well enough, if not, let me know and I will extend the description. I am highly thankful for any recommendations.
which()to find the rows which satisfy the conditions and then check the number of satisfactory rows usinglength(). Only if the length is greater than 'zero', try thesubset().