I am a new user of R and am more used to the loops functions with programs such as Matalab, but given R's strengths and weaknesses I am attempting to shy away from loops in favor of apply functions. The only problem is that I am not 100% sure when one should be favored over the other, for instance in the following scenario:
I have a series of data which I would like to convert to individual plots. I would like these plots to zoom in on a region of the plot by locating a specific point and then determining the xlim and ylim of the plot so that the graph only contains 80 or less points. This may or may not be the worse way to go about it, but it has worked.
And now for the code ((in German) Weg = distance , Kraft = Strain, Zeit = time):
#reads the data
mydata <- read.table(file, header = TRUE, skip=52, dec=",")
#establishes what segments of mydata are what
kraft <- mydata[,2]
weg <- mydata[,3]
zeit <- mydata[,1]
#Finds the distance values associated with the maximum force in the plot, which is the area in which I am interested
Weg_Values_at_Fmax <- weg[which(kraft == max(kraft))]
#the next sets of lines initiate the values which will be changed in the while loop
#one to zero, the other to a range of distance values on either side of the distance #values associated with the maximum force
n <- 0
Weg.index <- which((weg >= Weg_Values_at_Fmax[length(Weg_Values_at_Fmax)] -
Weg_Values_at_Fmax[length(Weg_Values_at_Fmax)]*(1/7) + n) &
weg <= (Weg_Values_at_Fmax[length(Weg_Values_at_Fmax)] +
Weg_Values_at_Fmax[length(Weg_Values_at_Fmax)]*(1/7) - n))
#finally the while loop which increase n (thereby decreasing Weg.index) until the #Weg.index falls below a certain value, in this case 80 points #
while(length(Weg.index) > 80){
n <- n + .0005
Weg.index <- which((weg >= Weg_Values_at_Fmax[length(Weg_Values_at_Fmax)] -
Weg_Values_at_Fmax[length(Weg_Values_at_Fmax)]*(1/6) + n) &
weg <= (Weg_Values_at_Fmax[length(Weg_Values_at_Fmax)] +
Weg_Values_at_Fmax[length(Weg_Values_at_Fmax)]*(1/6) - n))
}
Then comes the plotting:
plot(weg, kraft,
xlim=c(weg[Weg.index[1]], weg[Weg.index[length(Weg.index)]]),
ylim=c(min(kraft[Weg.index[1:length(Weg.index)]]),
max(kraft[Weg.index[1:length(Weg.index)]])),
main = file)
This code works fine as there is not too much data, but I am hoping that there is a more efficient way to handle such a data request with a while loop for when I need to crunch larger data. I hope that this question was specific enough and that it isn't too off topic or anything else like that. Thank you for your time and help.