Raster histogram excluding zeros in R

by ecologist1234   Last Updated April 16, 2019 05:22 AM

Simple question: In R, can I make a histogram of all the non-zero values in my raster? Some reproducible data below. I just want the histogram to be made with the zeros. Happy with a way to do that, or I guess to create a new raster that just removes all the zero-cells from r. Thanks.

y=seq(33,34,.1)
coords=expand.grid(x,y)
rdf=data.frame(coords,depth=runif(nrow(coords),0,2))
names(rdf)=c('x','y','value')
r=rasterFromXYZ(rdf)
plot(r)
hist(r)```


Answers 1


There isn't an assignment for x in the code above so I can't generate your exact output, but you should be able to plot non-0 entries in your histogram by using hist(r[r!=0]).

Edit: Here's an assignment for x (just a placeholder) and some artificially-crafted 0's for the raster values that demonstrate the difference between hist(r) and hist(r[r!=0]):

x = seq(-1,1,.1)
y=seq(33,34,.1)
coords=expand.grid(x,y)
rdf=data.frame(coords,depth=runif(nrow(coords),0,2))
names(rdf)=c('x','y','value')
rdf$value[23:30] = 0 #Added a few 0's to the value column
r=rasterFromXYZ(rdf)
plot(r)
hist(r)
hist(r[r!=0]) # Note reduction in count for lowest bin
JepsonNomad
JepsonNomad
April 16, 2019 04:30 AM

Related Questions


Updated December 04, 2018 23:22 PM

Updated January 10, 2019 14:22 PM

Updated January 09, 2018 19:22 PM

Updated September 27, 2018 16:22 PM

Updated August 17, 2017 07:22 AM