Hi Thiago, Something like this should work:
s <- stack(lapply(1:5, function(x) { r <- raster(nrows=22, ncols=20, xmn=-58, xmx=-48, ymn=-33, ymx=-22) r[] <- round(runif(22 * 20, min=0, max=600), digits=0) r })) intervals <- seq(0, 600, 100) vals <- sapply(1:nlayers(s), function(x) { # x <- 1 # Count frequencies and calculate percentage ## note: don't use df or t as object names--they are both functions tab <- table(cut(as.vector(s[[x]]), intervals, include.lowest=TRUE)) # ncells <- length(Which(!is.na(s[[x]]), cells = TRUE)) # alternative ncells <- sum(!is.na(s[[x]][])) DF <- data.frame(round(tab, digits=2))[, 2] }) # set up a column that decribes the rainfall bins/intervals ints <- cbind(intervals[-length(intervals)], intervals[-1]) bins <- apply(ints, 1, function(x) paste(x, collapse = "-")) # bind to output cbind.data.frame(bins, vals) On Wed, Feb 17, 2016 at 4:27 AM Thiago V. dos Santos < thi_vel...@yahoo.com.br> wrote: > Hi all, > > I am trying to count the frequency of values in raster objects based on > specified intervals. For example, I have a raster storing monthly rainfall > totals ranging from 50 to 600 mm. And I need to know how many values fall > in the interval 0-100, how many on 101-200, 201-300 and so on. > > I managed to do it in a single raster: > > require(raster) > > ## scratch a raster and fill some random values > r <- raster(nrows=22, ncols=20, xmn=-58, xmx=-48, ymn=-33, ymx=-22) > r[] <- round(runif(22 * 20, min=0, max=600), digits=0) > > # Count raster cells (excluding NA's) and set intervals > ncells <- sum(!is.na(r[])) > intervals <- seq(0, 600, 100) > > # Count frequencies and calculate percentage > t <- table(cut(as.vector(r), intervals, include.lowest=TRUE)) / ncells * > 100 > df <- data.frame(round(t, digits=2)) > > > However, how can I do the same for a raster stack, storing the count of > each layer in a column of the resulting data frame? > Thanks in advance, > -- Thiago V. dos Santos > > PhD student > Land and Atmospheric Science > University of Minnesota > > _______________________________________________ > R-sig-Geo mailing list > R-sig-Geo@r-project.org > https://stat.ethz.ch/mailman/listinfo/r-sig-geo > [[alternative HTML version deleted]] _______________________________________________ R-sig-Geo mailing list R-sig-Geo@r-project.org https://stat.ethz.ch/mailman/listinfo/r-sig-geo