1

I try to calculate the frequency/count of pixel values of a raster in R using freq().

library(raster)
RastSmall <- raster(nrow=70, ncol=70) 
RastBig   <- raster(nrow=7000, ncol=7000) 
set.seed(0)
RastSmall[] <- round(runif(1:ncell(r_hr), 1, 5))
RastBig[] <- round(runif(1:ncell(r_hr), 1, 5))

freq(RastSmall)
value    count
[1,]     1  6540000
[2,]     2 12150000
[3,]     3 12140000
[4,]     4 11720000
[5,]     5  6450000  

However, it is a fairly large file and takes extremely long, i.e. up to hours. Is there a faster way in R?

system.time(freq(RastSmall))
  user  system elapsed 
  0.008   0.000   0.004 
system.time(freq(RastBig))
  user  system elapsed 
  40.484   0.964  41.445 

Is there a way to speed this up? Alternatively can this be done in the command line using something like gdal tools?

However, it is a fairly large file and takes extremely long. Is there a faster way in R? Alternatively can this be done in the command line using something like gdal or AWK?

3

You could try pkstat from the pktools package to achieve this. Specifically, you will need to add the options -hist and set the number of bins (categories) using -nbins. For instance:

pkstat -i input.tif -hist -nbins 5
  • Thanks for the suggestion. Does pkstat also work without bins? – mace Mar 24 '17 at 16:56
  • 1
    yes, it is just one option. – dmci Mar 24 '17 at 17:01
  • 1
    here the syntax to export it into a text file that can than be imported in R: pkstat -i input.tif -hist > counts.txt 2>&1 – mace Mar 25 '17 at 14:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.