[R-sig-Geo] Count frequency in raster stacks

Thiago V. dos Santos thi_veloso at yahoo.com.br
Thu Feb 18 01:54:16 CET 2016


Hi Lyndon,
You were right - it worked like a charm. Thank you so much. Greetings, -- Thiago V. dos Santos
PhD studentLand and Atmospheric ScienceUniversity of Minnesota 

    On Wednesday, February 17, 2016 5:04 AM, Lyndon Estes <lyndon.estes at gmail.com> wrote:
 

 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/intervalsints <- cbind(intervals[-length(intervals)], intervals[-1])bins <- apply(ints, 1, function(x) paste(x, collapse = "-"))
# bind to outputcbind.data.frame(bins, vals)

On Wed, Feb 17, 2016 at 4:27 AM Thiago V. dos Santos <thi_veloso at 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 at r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo



  
	[[alternative HTML version deleted]]



More information about the R-sig-Geo mailing list