I just picked up R this summer.
I created a nested for loop so that nls() will be performed in 24 raster layers and a new file will be created to save the data.
In this example, I have a raster stack of 48 layers worth 2 years of data. My for loop will perform the calculation in each year which consists of 24 layers, write a new ENVI file and proceed to the next year.
I managed to create a files for i = 1 and i = 2. However, R does not stop after creating new ENVI files. It is loading for forever and the temporary files in my C drive is updating from time to time (C:\Users\CandiceYingWoei\AppData\Local\Temp\Rtmp is empty, but the date modified keeps updating).
I tried to use break to stop the for loop. I think it is not necessary because i will never go over nyears since I already set i in (1:nyears). if (i > nyears) { break }
How do I stop R after creating the files?
library(sp)
library(raster)
library(ncdf4)
library(rgdal)
setwd("C:/")
new <- stack("82_83_test.envi")
nlayers <- nlayers(new)
nyears <- nlayers(new)/24
for (i in 1:nyears) {
for (j in (1+(24*(i-1))):(24*i)) {
fun<- function(x) {
# a function that perform nls through each pixel in all raster
# layers in each year and return several parameters (SOS, EOS, etc).
return (c(SOS,EOS,LOS,SPUDOY,P_TAmplitude))
}
equation<-calc(new[[(1+(24*(i-1))):(24*i)]],fun,forceapply=TRUE)
date<- 1981+i
name<-paste("Output_",date,".envi",sep="")
writeRaster(equation,filename=name,format="ENVI",overwrite=T)
# this is where the break statement is located
if (i > nyears) { break }
}
}