Search code examples
rlapplyshapefiler-raster

Extract coordinates from multiple datasets R


I have found problems to extract raster values from multiple dataframes with coordinate of longitude and latitude using specific geographic region obtained from shapefiles. All the geographical region are in different extent and have a corresponding occurrence dataframe of coordinate data. I tried using mask function from raster package:

First - load shapefiles, raster layers, and dataframes as list

shp<-list.files(pattern = "shp")
shape<-lapply(shp,readShapeSpatial,proj4string=CRS("+proj=longlat +ellps=WGS84"))

rastFiles<-list.files(pattern="bil") #List of bioclimatic variables 
layers<-stack(rastFiles)

oco<-list.files(pattern = ".csv")
oco<-lapply(oco,read.table,header=T,sep = ",")
oco<-lapply(oco,"[", c(6,5))
y<-lapply(oco, na.omit)

Second - manipulate shapefiles, crop raster layers and create a mask with geographical extension that I need.

p<- lapply(shape, function(i) {
    i[i@data$ORIGIN==1,] #specifying the region of shapefile
    p1<-SpatialPolygons(i@polygons,proj4string=i@proj4string) #transform specific region in shapefile
    nr<-crop(layers,extent(p1)) #crop raster stack with polygons extent
    m<-mask(nr,p1) #raster mask using poligon as model
    })

As result, the object "p" is a list with RasterBrick objects. For extract the cell values coordinates from each data frames, I tried

value<-lapply(p,extract,y)

the console returns me that:

Error in round(y) : non-numeric argument to mathematical function

After checking the structure of "p" I found that the raster values are non available:

.. ..@ data    :Formal class '.MultipleRasterData' [package "raster"] with 14 slots
.. .. .. ..@ values    : int [1:99660, 1:20] NA NA NA NA NA NA NA NA NA NA ...

However, I can extract one by one dataframe values in a rasterstack using list operators:

extract(nat[[1]],y[[1]])

In this way I have searched to understand why my lapply function for values don't work.

Thank's for your help!


Solution

  • Just looking at your last line of code, I'm assuming you want to apply the same function (extract) on 1st elements of nat and y, then 2nd elements of both, etc. This is what mapply does. So, your code will look like this:

    mapply(extract, nat, y)