Lihsin Wu
Lihsin Wu

Reputation: 33

Masking raster from data in SpatialGridDataFrame and SpatialPolygonsDataFrame

I am trying to mask a raster file by including only some specific area (‘Koeppen Geiger’ climatic zones) with several locations. I got an error message running the final line of code:

Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘mask’ for signature ‘"SpatialGridDataFrame", "SpatialPolygonsDataFrame"’

.

    ##Read Countries file
library(sp)
library(maptools)
library(rworldmap)
countries = readShapeSpatial("D:/Studies/PhD/SCI/modeling/ne_10m_admin_0_countries/ne_10m_admin_0_countries.shp") [enter link description here][1]
asia.zone = countries[countries$ADMIN=="South Korea"|
                        countries$ADMIN=="North Korea"|
                        countries$ADMIN=="Japan"|
                        countries$ADMIN=="China"|
                        countries$ADMIN=="Taiwan",]

##Read Koeppen Geiger’ climatic zones
tst <- read.csv('D:/Studies/PhD/SCI/modeling/Koeppen-Geiger-ASCII.csv',as.is=TRUE) [enter link description here][1]
tst.l <- tst [tst$Cls=="Cfc"|
                tst$Cls=="Cfa"|
                tst$Cls=="Cfb"|
                tst$Cls=="Cwa"|
                tst$Cls=="Cwb"|
                tst$Cls=="Aw"|
                tst$Cls=="As"|
                tst$Cls=="Am"|
                tst$Cls=="Dwd"|
                tst$Cls=="Dwb"|
                tst$Cls=="Dwa"|
                tst$Cls=="Dwc",]
#convert to sp SpatialPointsDataFrame
coordinates(tst.l) = c("Lon", "Lat")
# promote to SpatialPixelsDataFrame
gridded(tst.l) <- TRUE
# promote to SpatialGridDataFrame
tst.lsGDF = as(tst.l, "SpatialGridDataFrame")
# mask the specific climate zone from some locations
asia.zone2 <- mask(tst.lsGDF,asia.zone)

Upvotes: 1

Views: 4589

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47546

If you look up ?mask you will see that it has been implemented for Raster* objects, not for SpatialGridDataFrame objects. So you need to coerce your data to a Raster object. Something like this might work:

library(raster)
setwd("D:/Studies/PhD/SCI/modeling/")
countries <- shapefile("vne_10m_admin_0_countries/ne_10m_admin_0_countries.shp")
asia.zone <- countries[countries$ADMIN %in% c("South Korea", "North Korea","Japan", "China", "Taiwan"), ]

tst <- read.csv("Koeppen-Geiger-ASCII.csv", stringsAsFactor=FALSE) 
tst.l <- tst [tst$Cls %in% c("Cfc", "Cfa", "Cfb", "Cwa", "Cwb", "Aw", "As", "Am", "Dwd", "Dwb", "Dwa", "Dwc"),]

coordinates(tst.l) = c("Lon", "Lat")
# promote to SpatialPixelsDataFrame
gridded(tst.l) <- TRUE
r <- raster(tst.l)

asia.zone2 <- mask(r, asia.zone)

Upvotes: 2

Related Questions