Search code examples
rshapefiler-sprgdal

How to read results from a shapefile using readOGR from the rgdal package in R?


So I read my shapefile easily:

shape<-readOGR(".","shapefile")

then if I do head(shape,1) I get the following result:

An object of class "SpatialLinesDataFrame"
Slot "data":
  ID NAME PROJECT       UP      DOWN
0  1   X    05076     110468    38282
Slot "lines":
[[1]]
An object of class "Lines"
Slot "Lines":
[[1]]
An object of class "Line"
Slot "coords":
        [,1]     [,2]
[1,] 1824583 547917.9
[2,] 1824544 547437.1

Slot "ID":
[1] "0"

Slot "bbox":
        min       max
x 1824543.9 1824583.4
y  547437.1  547917.9

Slot "proj4string":
CRS arguments: NA 

So getting the data is easy, I just do shape$NAME and I get all the names from the data.

But I don't know how to access the place where it says Slot "coords" which is what I want to access... or for that matter, how do I access things that are not on the data slot?

In other words, i want to read the shapefile and end up with a variable equal to 1824583, which is the top left value of the coords slot matrix.

Anyone can help?


Solution

  • We can use @ to access the slots. Here I used the meuse dataset as an example.

    library(sp)
    
    data(meuse)
    coordinates(meuse) <- ~x+y
    proj4string(meuse) <- CRS("+init=epsg:28992")
    
    head(meuse@coords)
    #        x      y
    # 1 181072 333611
    # 2 181025 333558
    # 3 181165 333537
    # 4 181298 333484
    # 5 181307 333330
    # 6 181390 333260
    
    meuse@coords[1, 1]
    # [1] 181072