Skip to content
Prev 24726 / 29559 Next

Incorrect month order in zApply function

Hi Vijay,

Whoops!  I think you misunderstood my message - I didn't think I was pointing out a mistake on your part.  My 'uhoh' was pointing out surprising behavior on the part of zApply.

If I use my earlier edited example and remove the "name=" argument to zApply, the results still make my forehead get all wrinkled up as the month labels don't align with the results.

library(raster)

# Create date sequence
idx <- seq(as.Date("1996/1/1"), as.Date("1996/12/31"), by = "day")
mon_num <- as.numeric(format(idx, "%m"))

# Create raster stack and assign dates
r <- raster(ncol=5, nrow=5)
s <- stack(
    lapply(1:length(idx), 
        function(x) setValues(r, rep(mon_num[x],ncell(r)))
        )
    )
s <- setZ(s, idx)

# Calculate monthly average
x <- zApply(s, by=months, fun = mean)
x
#class       : RasterBrick 
#dimensions  : 5, 5, 25, 12  (nrow, ncol, ncell, nlayers)
#resolution  : 72, 36  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
#data source : in memory
#names       : April, August, December, February, January, July, June, March, May, November, October, September 
#min values  :     1,      2,        3,        4,       5,    6,    7,     8,   9,       10,      11,        12 
#max values  :     1,      2,        3,        4,       5,    6,    7,     8,   9,       10,      11,        12 
#            : April, August, December, February, January, July, June, March, May, November, October, September 


So, what the heck does the "by=" do if not group the layers by month?  I can't see why you need to define your own aggregation m() to get it to work (and I am impressed that you did get it to work.)

Cheers,
Ben
Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Report Gulf of Maine jellyfish sightings to jellyfish at bigelow.org or tweet them to #MaineJellies -- include date, time, and location, as well as any descriptive information such as size or type.  Learn more at https://www.bigelow.org/research/srs/nick-record/nick-record-laboratory/mainejellies/