Search code examples
for-loopmatrixcountextractraster

extracting values from maps and inserting into a summary table


I have several maps that I am working with. I want to extract the values (1, 0 and NA) from the maps and place them all into a summary matrix. Since I have so many maps, I think its best to do this as a for loop. This is the code I have so far and my maps and empty summary matrix are uploaded to my Dropbox here: DATASET here

setwd ('C:/Users/Israel/Dropbox/')
require (raster)
require(rgdal)
require (plyr)

#load in the emxpy matrix to be filled
range.summary<-read.csv('range_sizes.csv', header=T)

#load in maps and count pixels 
G1.total<-raster('Group1/Summary/PA_current_G1.tif')
G1.total.df<-as.data.frame(G1.total)

#these are the values I need to be placed into the empty matrix (range.summary)
count (G1.total.df)

  PA_current_G1   freq
1             0 227193
2             1 136871
3            NA 561188

Solution

  • Try this

    I downloaded 3 images

    library(raster)
    wd <- 'D:\\Programacao\\R\\Stackoverflow\\raster'
    allfiles <- list.files(file.path(wd), all.files = F)
    # List of TIF files at dir.fun folder
    tifs <- grep(".tif$", allfiles, ignore.case = TRUE, value = TRUE) 
    #stack rasterLayer 
    mystack <- stack(file.path(wd, tifs))
    # calculate frequencies
    freqs <- freq(mystack, useNA='ifany')
    # rbind list to get a data.frame
    freqsdf <- do.call(rbind.data.frame, freqs)
    freqsdf
                        value  count
    PA_2050_26_G1.1         0 256157
    PA_2050_26_G1.2         1 193942
    PA_2050_26_G1.3        NA 475153
    PA_2050_26_G2.1         0 350928
    PA_2050_26_G2.2         1  99171
    PA_2050_26_G2.3        NA 475153
    PA_2050_26_sub_G1.1     0 112528
    PA_2050_26_sub_G1.2     1  90800
    PA_2050_26_sub_G1.3    NA 721924
    
    str(freqsdf)
    'data.frame':   9 obs. of  2 variables:
     $ value: num  0 1 NA 0 1 NA 0 1 NA
     $ count: num  256157 193942 475153 350928 99171 ...
    

    Now it is a matter of work the output shape.