I have two distinct tasks to complete- find the index of the maximum value in each cell of a stack of 12 rasters. There are 12 rasters because each raster is the mean monthly precipitation over 30 years. Then I want to reorder another raster stack of 360 layers, where each layer is the monthly precip over 30 years such that the resulting raster stack has cells that start at the index found to be the of the 12 mean monthly precip values and then continues with the rest of the monthly precip values.
So for example, I have monthly precip values Jan -Dec 1981, 1982 etc. However, I have found that the wettest month is July i.e. 7th month), so I want to reorder such for each pixel the stack starts from July 1981 until Dec 2020.
If I were to do this with a list of vector and not rasters, I would do
twleve_values<-c(11.630832 19.372524 16.788150 4.051670 14.857163 186.173774 420.738594 304.162227 161.079527 23.955036 8.945979 3.019485)
max_tweleve_value<-which.max(twelve_values) #this would result in 7 because the max value 420.738 is the 7th value
if(max_twelve_value > 1) other_360_values[c(max_twelve_value:(length(other_360_values) - (13-max_twelve_value)))] else other_360_values
I am stuck at the first task of finding the index of the wettest month in the stack of 12 rasters. I have tried
x<-stackApply(12_raster_stack, indices = rep(1,12), fun=which.max, na.rm = TRUE)
Error in FUN(newX[, i], ...) : unused argument (na.rm = TRUE) and
x<-calc(mean_monthly_ppt, fun= whiches.max)
Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) : cannot use this function
How do I move ahead?
sort.int
with the index.return = TRUE argument. It allows you to sort a vector AND returns the index of the sort. As such you can use this index to referent the order in the raster stack. It does not make much sense to reorder your pixels but, you could calculate a global max for each raster, store in a vector and then pass this vector tosort.int
. The raster stack could then be reordered using the resulting index values in a double bracket. Something liker[[sort.int(max.vals, index.return = TRUE)$ix]]